PHP Delete File
Summary: in this tutorial, you will learn how to delete a file in PHP using the unlink() function.
Introduction to the PHP delete file function
To delete a file, you use the unlink() function:
The unlink() function has two parameters:
- $filename is the full path to the file that you want to delete.
- $context is a valid context resource.
The unlink() function returns true if it deletes the file successfully or false otherwise. If the $filename doesn’t exist, the unlink() function also issues a warning and returns false .
PHP delete file examples
Let’s take some examples of using the unlink() function.
1) Simple PHP delete file example
The following example uses the unlink() function to delete the readme.txt file:
2) Delete all files in a directory that match a pattern
The following example deletes all files with the .tmp extension:
- First, define a variable that stores the path to the directory in which you want to delete files.
- Second, use the glob() function to search for all files in the directory $dir that has the *.tmp extension and pass it result to the array_map() function to delete the files.
Generally, you can change the pattern to delete all matching files in a directory using the array_map() , unlink() and glob() functions.
unlink
Удаляет файл filename . Функция похожа на функцию unlink() Unix в C. При неудачном выполнении будет вызвана ошибка уровня E_WARNING .
Список параметров
Если файл является символической ссылкой, символическая ссылка будет удалена. В Windows для удаления символической ссылки на каталог вместо этого должна использоваться функция rmdir() .
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
| Версия | Описание |
|---|---|
| 7.3.0 | В Windows теперь можно удалить файлы функцией unlink() с использованием дескрипторов, хотя раньше это не удавалось. Тем не менее, всё ещё невозможно повторно создать удалённый файл, пока все дескрипторы к нему не будут закрыты. |
Примеры
Пример #1 Пример простого использования unlink()
<?php
$fh = fopen ( ‘test.html’ , ‘a’ );
fwrite ( $fh , ‘<h1>Привет, мир!</h1>’ );
fclose ( $fh );
Смотрите также
- rmdir() — Удаляет директорию
User Contributed Notes 12 notes
This will delete all files in a directory matching a pattern in one line of code.
<?php array_map ( ‘unlink’ , glob ( «some/dir/*.txt» )); ?>
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.
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 .
Here the simplest way to delete files with mask
<?php
$mask = «*.jpg»
array_map ( «unlink» , glob ( $mask ) );
?>
if you’re looking for a recursive unlink:
<?php
/**
* 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 ));
>
>
?>
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 );
>
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:
<?php
// First close the file
fclose ( $fp );
// Then unlink 🙂
unlink ( $somefile );
?>
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.
<?php
$old = getcwd (); // Save the current directory
chdir ( $path_to_file );
unlink ( $filename );
chdir ( $old ); // Restore the old working directory
?>
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.
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.
How to delete a file via PHP?
How do I delete a file from my server with PHP if the file is in another directory?
Here is my page layout:
- projects/backend/removeProjectData.php (this file deletes all my entries for the database and should also delete the related file)
- public_files/22.pdf (the place where the file is located.)
I’m using the unlink function:
But this always gives me an error that the file does not exist. Any ideas?
6 Answers 6
The following should help
-
— Returns canonicalized absolute pathname — Tells whether the filename is writable — Deletes a file
Run your filepath through realpath, then check if the returned path is writable and if so, unlink it.
![]()
![]()
![]()
Check your permissions first of all on the file, to make sure you can a) see it from your script, and b) are able to delete it.
You can also use a path calculated from the directory you’re currently running the script in, eg:
(in PHP 5.3 I believe you can use the __DIR__ constant instead of dirname() but I’ve not used it myself yet)
You can delete the file using
but if you are deleting a file from it’s http path then this unlink is not work proper. You have to give a file path correct.
![]()
AIO solution, handles everything, It’s not my work but I just improved myself. Enjoy!
I know this question is a bit old, but this is something simple that works for me very well to delete images off my project I’m working on.
The dirname(__FILE__) section prints out the base path to your project. The /img/tasks/ are two folders down from my base path. And finally, there’s my image I want to delete which you can make into anything you need to.
With this I have not had any problem getting to my files on my server and deleting them.
Удаление файлов и папок в PHP
PHP – куда больше, чем просто язык для обработки различных форм обратной связи на сайтов. Одним из примеров использования, который подойдёт начинающим вебмастерам, выступает работа с файлами. В частности, речь идёт об удалении документов и директорий с сервера, возможном с помощью встроенного в язык набора функций.
Обзор функции
Прежде всего стоит обратить внимание на супермассив $_SERVER, который содержит в себе элементы, нужные для работы с файлами. Речь идёт о конкретно $_SERVER[‘DOCUMENT_ROOT’], который возвращает абсолютный путь сервера. Под этим термином подразумевается расположение папки public_html, в которую помещается видимое пользователям содержимое ресурса, с точки зрения сервера. То есть, просто скопировать URL из адресной строки браузера не выйдет.
Сам процесс удаления производится с помощью unlink(). Учтите, что влияние этой функции распространяется только на файлы, а не на директории. Для работы с каталогами следует задействовать rmdir(), которая срабатывает, только если в папке нет никаких документов.
Для директории должны быть выставлены соответствующие разрешения, позволяющие удалять её содержимое (например, можно выставить 0777 для полного доступа в системе). В любом случае, вам сначала потребуется программного или вручную удалить содержимое папки. С помощью кода с задействованием scandir() можно сделать это, представив название файлов в директории в виде массива, и потом обработав их с помощью rmdir().
Учтите, что настройки безопасности системы не дадут вам удалить некоторое содержимое. Посредством PHP нельзя не только убрать файлы при отсутствии соответствующего кода разрешения (например, при 0000), но и очистить системные каталоги.
Тем не менее, можно будет сделать это через функцию exec(), которая вводит команды прямо в терминал ОС, но, к сожалению, является запрещённой во многих веб-хостингах. Это делается из соображений безопасности. Если же сайт находится на собственном VDS, можно отключить блокировку exec() посредством конфигурации PHP. При этом команды будут отличаться в зависимости от операционной системы.
Для самого простого пользования unlink() достаточно указать путь к файлу, как в примерах ниже. У него, как и у rmdir(), есть ещё и второй аргумент $context, однако его задействование необязательно и нужно лишь в довольно редких случаях.
Примеры использования
Удаление файла с проверкой
Поскольку unlink() возвращает true при успешном выполнении, а false и ошибку класса E_WARNING при неудаче, можно проверить результат выполнения посредством if-elseif-else.