unlink
Удаляет файл filename . Функция похожа на функцию unlink() Unix в C. При неудачном выполнении будет вызвана ошибка уровня E_WARNING .
Список параметров
Если файл является символической ссылкой, символическая ссылка будет удалена. В Windows для удаления символической ссылки на каталог вместо этого должна использоваться функция rmdir() .
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
| Версия | Описание |
|---|---|
| 7.3.0 | В Windows теперь можно удалить файлы функцией unlink() с использованием дескрипторов, хотя раньше это не удавалось. Тем не менее, всё ещё невозможно повторно создать удалённый файл, пока все дескрипторы к нему не будут закрыты. |
Примеры
Пример #1 Пример простого использования unlink()
$fh = fopen ( ‘test.html’ , ‘a’ );
fwrite ( $fh , ‘
Привет, мир!
‘ );
fclose ( $fh );
?php
Смотрите также
- rmdir() — Удаляет директорию
User Contributed Notes 12 notes
11 years ago
This will delete all files in a directory matching a pattern in one line of code.
12 years ago
Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS?
The unlink() is not about removing file, it’s about removing a file name. The manpage says: «unlink — delete a name and possibly the file it refers to».
Most of the time a file has just one name — removing it will also remove (free, deallocate) the `body’ of file (with one caveat, see below). That’s the simple, usual case.
However, it’s perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive’, so to say. Only when all the names are removed, the body of file actually is freed.
The caveat:
A file’s body may *also* be `kept alive’ (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there’s a fancy way of resurrecting a file removed by a mistake but still held open by a process.
9 years ago
unlink($fileName); failed for me .
Then i tried using the realpath($fileName) function as
unlink(realpath($fileName)); it worked
just posting it , in case if any one finds it useful .
12 years ago
Here the simplest way to delete files with mask
$mask = «*.jpg»
array_map ( «unlink» , glob ( $mask ) );
?>
19 years ago
To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function. Say I wanted to delete all jpgs .
foreach ( glob ( «*.jpg» ) as $filename ) echo » $filename size » . filesize ( $filename ) . «\n» ;
unlink ( $filename );
>
15 years ago
I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.
Though, I have been breaking my head for about an hour on why I couldn’t get my persmissions right to unlink the main file.
Finally I knew what was wrong: because I was working on the file and hadn’t yet closed the file, it was still in use and ofcourse couldn’t be deleted 🙂
So I thought of mentoining this here, to avoid others of making the same mistake:
// First close the file
fclose ( $fp );
// Then unlink 🙂
unlink ( $somefile );
?>
15 years ago
To anyone who’s had a problem with the permissions denied error, it’s sometimes caused when you try to delete a file that’s in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with «../»).
So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.
$old = getcwd (); // Save the current directory
chdir ( $path_to_file );
unlink ( $filename );
chdir ( $old ); // Restore the old working directory
?>
9 years ago
This might seem obvious, but I was tearing my hair out with this problem — make sure the file you’re trying to delete isn’t currently being used. I had a script that was parsing a text file and was supposed to delete it after completing, but kept getting a permission denied error because I hadn’t explicitly closed the file, hence it was technically still being «used» even though the parsing was complete.
1 year ago
if you’re looking for a recursive unlink:
/**
* delete a file or directory
* automatically traversing directories if needed.
* PS: has not been tested with self-referencing symlink shenanigans, that might cause a infinite recursion, i don’t know.
*
* @param string $cmd
* @throws \RuntimeException if unlink fails
* @throws \RuntimeException if rmdir fails
* @return void
*/
function unlinkRecursive ( string $path , bool $verbose = false ): void
if (! is_readable ( $path )) return;
>
if ( is_file ( $path )) if ( $verbose ) echo «unlink: < $path >\n» ;
>
if (! unlink ( $path )) throw new \RuntimeException ( «Failed to unlink < $path >: » . var_export ( error_get_last (), true ));
>
return;
>
$foldersToDelete = array();
$filesToDelete = array();
// we should scan the entire directory before traversing deeper, to not have open handles to each directory:
// on very large director trees you can actually get OS-errors if you have too many open directory handles.
foreach (new DirectoryIterator ( $path ) as $fileInfo ) if ( $fileInfo -> isDot ()) continue;
>
if ( $fileInfo -> isDir ()) $foldersToDelete [] = $fileInfo -> getRealPath ();
> else $filesToDelete [] = $fileInfo -> getRealPath ();
>
>
unset( $fileInfo ); // free file handle
foreach ( $foldersToDelete as $folder ) unlinkRecursive ( $folder , $verbose );
>
foreach ( $filesToDelete as $file ) if ( $verbose ) echo «unlink: < $file >\n» ;
>
if (! unlink ( $file )) throw new \RuntimeException ( «Failed to unlink < $file >: » . var_export ( error_get_last (), true ));
>
>
if ( $verbose ) echo «rmdir: < $path >\n» ;
>
if (! rmdir ( $path )) throw new \RuntimeException ( «Failed to rmdir < $path >: » . var_export ( error_get_last (), true ));
>
>
?>
8 years ago
On OSX, when fighting against a «Permission Denied» error, make sure, the directory has WRITE permissions for the executing php-user.
Furthermore, if you rely on ACLs, and want to delete a file or symlink, the containing directory needs to have «delete_child» permission in order to unlink things inside. If you only grant «delete» to the folder that will allow you to delete the container folder itself, but not the objects inside.
3 years ago
unlink works the same as the rm command on nix based loses or del command on windows, it will not resolve the file but remove the exact path given even if that path is just a link.
E.G
/var/www/test/index.php = symlink(/home/test/www/index.php)
unlink ( «/var/www/test/index.php» );
?>
Will just delete the link, not the original file where as
unlink ( «/home/test/www/index.php» );
?>
Will unlink the original file path and break the symlink, and allow the system to overwrite as the filesystem will not know of the file’s location anymore.
10 years ago
The best way to delete files by mask is as follows:
array_walk ( glob ( ‘/etc/*’ ), ‘unlink’ );
?>
Do not use array_map mentioned below — it’s purpose is to process values in a given array AND COLLECT data returned by the callback function. So, array_map is slower and uses additional memory compared to array_walk.
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
How to Uninstall PHP in Windows 10
I have installed php and pulled the package through powershell with this command : Set-ExecutionPolicy RemoteSigned; Invoke-WebRequest -Uri «https://github.com/cretueusebiu/valet-windows/raw/master/bin/php71.ps1″ -OutFile $env:temp\php71.ps1; .»$env:temp\php71.ps1» And I found out that MYSQL doesn’t come with it, now I want to install xampp and just replace it. How am I gonna delete my installed php in the computer ?
asked Jan 4, 2018 at 12:40
2,698 10 10 gold badges 42 42 silver badges 69 69 bronze badges
1 Answer 1
PHP on windows doesn’t exactly «install» like Python or something, it will probably download to wherever you ran the script from. Remove this folder and:
- Open Control Panel
- Open System
- Click Advanced System Settings on the left
- Click Environment Variables at the bottom right
- Find «PATH» line in the «System Variables» box (bottom half)
- Click this line and click Edit
- Find the line that ends in «php»
- Highlight and Delete this line
The XAMPP installer should then register it’s own PHP version, but to verify you could repeat these steps but make sure the line that ends in «php» is referring to the folder in which you installed XAMPP
Uninstall PhpStorm
The proper way to remove PhpStorm depends on the method you used to install it.
Uninstall using the Toolbox App
If you installed PhpStorm using the Toolbox App, do the following:
- Open the Toolbox App, click the settings icon for the necessary instance, and select Uninstall .
Uninstall a standalone instance
If you are running a standalone PhpStorm instance, the default IDE directories are preserved when you remove your instance in case you want to keep your settings for later or to use them with another instance, another version, or another IDE. You can remove those directories if you are sure you won’t need them.
- Open the Apps & Features section in the Windows Settings dialog, select the PhpStorm app and click Uninstall . Depending on your version of Windows, the procedure for uninstalling programs may be different. You can also manually run Uninstall.exe in the installation directory under /bin .
- Remove the following directories: Syntax %APPDATA%\JetBrains\%LOCALAPPDATA%\JetBrains\Example C:\Users\JohnS\AppData\Roaming\JetBrains\PhpStorm2023.2 C:\Users\JohnS\AppData\Local\JetBrains\PhpStorm2023.2
- Delete the PhpStorm application in the Applications directory.
- Remove the following directories: Syntax ~/Library/Application Support/JetBrains/~/Library/Caches/JetBrains/Example ~/Library/Application Support/JetBrains/PhpStorm2023.2 ~/Library/Caches/JetBrains/PhpStorm2023.2
- Delete the installation directory.
- Remove the following directories: Syntax ~/.config/JetBrains/~/.cache/JetBrains/~/.local/share/JetBrains/Example ~/.config/JetBrains/PhpStorm2023.2 ~/.cache/JetBrains/PhpStorm2023.2 ~/.local/share/JetBrains/PhpStorm2023.2
The default location of the IDE directories has changed starting from PhpStorm version 2020.1. If you had a previous version, new installations will import configuration from the old directories. For more information about the location of the default directories in previous IDE versions, see the corresponding help version, for example: https://www.jetbrains.com/help/phpstorm/2019.3/tuning-the-ide.html#default-dirs.
Uninstall silently on Windows
You can run the uninstaller with the /S switch as an administrator. The uninstaller is located in the installation directory under bin .
Run cmd (Windows Command Prompt) as administrator, change to the PhpStorm installation directory, and run the following:
bin\uninstall.exe /S
Uninstall the snap package on Linux
If you installed PhpStorm as a snap package, use the following command to remove it:
Как удалить php windows 10
Как удалить установку PHP установщика веб-платформы (WPI)?
Мы установили PHP на Windows Server 2008 R2 с помощью установщика веб-платформы (WPI) 3.0.x.
Тем не менее, я хотел бы удалить PHP (в частности, 5.3, оставив 5.2 как есть). К сожалению, опция удаления не существует в программах и компонентах, и в прошлом я только обновлял установки PHP, и мне не приходилось удалять. (Судя по отсутствию ответов, которые я нашел в Интернете, похоже, что в общем случае это тоже так.)
Я понимаю, что могу оставить дополнительную установку там, но ради чистого сервера и того, чтобы было достаточно очевидно, какая версия PHP используется, я бы хотел удалить установку.
Я полагаю, я мог бы также удалить каталог установки — C: \ Program Files (x86) \ PHP \ v5.3 — но это не так.
PHP Manager также установлен (также через WPI), но я не вижу способа удалить установку, только добавить.
Эта ссылка содержит инструкции о том, как вручную удалить версию PHP из IIS в Windows 7. Я думаю, что инструкции для Windows Server 2008 будут аналогичными. Кажется, что вам нужно отредактировать файл applicationHost.config и удалить папку.
Откройте файл% userprofile% \ documents \ iisexpress \ config \ applicationhost.config и:
Найдите следующую запись (или аналогичную запись) в файле applicationhost.config и прокомментируйте или удалите ее.
Найдите следующую запись в разделе hanlders и прокомментируйте ее или удалите.
Как удалить PHP в Windows 10
Я установил php и вытащил пакет через powershell с помощью этой команды:
Set-ExecutionPolicy RemoteSigned; Invoke-WebRequest -Uri » https://github.com/cretueusebiu/valet-windows/raw/master/bin/php71.ps1 » -OutFile $ env: temp\php71.ps1;. «$ ENV: Temp\php71.ps1»
И я узнал, что MYSQL не приходит с этим, теперь я хочу установить xampp и просто заменить его. Как я могу удалить установленный php на компьютере?
PHP на windows не точно «устанавливает», как Python, или что-то еще, он, вероятно, будет загружаться туда, откуда вы запускали скрипт. Удалите эту папку и:
- Открыть панель управления
- Открытая система
- Нажмите «Дополнительные системные настройки» слева
- Нажмите «Переменные среды» в правом нижнем углу
- Найдите строку «PATH» в поле «Системные переменные» (нижняя половина)
- Нажмите эту строку и нажмите «Изменить».
- Найдите строку, которая заканчивается на «php»
- Выделить и удалить эту строку
Затем установщик XAMPP должен зарегистрировать собственную версию PHP, но чтобы убедиться, что вы можете повторить эти шаги, но убедитесь, что строка, заканчивающаяся на «php», относится к папке, в которой вы установили XAMPP
powershell — Как удалить PHP в Windows 10
Я установил php и вытащил пакет через powershell с помощью этой команды:
И я обнаружил, что MYSQL не поставляется с ним, теперь я хочу установить xampp и просто заменить его. Как мне удалить мой установленный php на компьютере?
Решение
PHP на Windows не «устанавливает» точно так же, как Python или что-то в этом роде, он, вероятно, будет загружаться туда, откуда вы запускали скрипт. Удалить эту папку и:
- Открытая панель управления
- Открытая система
- Нажмите Расширенные настройки системы слева
- Нажмите Переменные среды в правом нижнем углу
- Найдите строку «ПУТЬ» в поле «Системные переменные» (нижняя половина)
- Нажмите на эту строку и нажмите Редактировать
- Найдите строку, которая заканчивается на «php»
- Выделите и удалите эту строку
Затем установщик XAMPP должен зарегистрировать свою собственную версию PHP, но для проверки вы можете повторить эти шаги, но убедитесь, что строка, заканчивающаяся на «php», ссылается на папку, в которую вы установили XAMPP
Похожие публикации:
- Как удалить все с компьютера windows 10 кроме windows
- Как удалить папку windows old в windows 10
- Как удалить папку windows old в windows 7
- Как удалить windows movie maker из windows 7
