Как очистить директорию php

PHP: Delete all files from a folder.

In this guide, we are going to show you how to delete all files in a folder using PHP.

Our first example is pretty straight-forward, as we simply loop through the files and then delete them.

Take a look at the following code sample.

//The name of the folder. $folder = 'temporary_files'; //Get a list of all of the file names in the folder. $files = glob($folder . '/*'); //Loop through the file list. foreach($files as $file) < //Make sure that this is a file and not a directory. if(is_file($file))< //Use the unlink function to delete the file. unlink($file); >>
  1. In this example, we will be deleting all files from a folder called “temporary_files”.
  2. We list the files in this directory by using PHP’s glob function. The glob function basically finds pathnames that match a certain pattern. In this case, we use a wildcard (asterix) to specify that we want to select everything that is inside the “temporary_files” folder.
  3. The glob function returns an array of file names that are in the specified folder.
  4. We then loop through this array.
  5. Using the is_file function, we check to see if it is a file and not a parent directory or a sub-directory.
  6. Finally, we use the unlink function, which deletes the file.

Deleting files in sub-folders.

To delete all files and directories in all sub-directories, we can use recursion.

Читайте также:  W3c html img src

Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.

function deleteAll($str) < //It it's a file. if (is_file($str)) < //Attempt to delete it. return unlink($str); >//If it's a directory. elseif (is_dir($str)) < //Get a list of the files in this directory. $scan = glob(rtrim($str,'/').'/*'); //Loop through the list of files. foreach($scan as $index=>$path) < //Call our recursive function. deleteAll($path); >//Remove the directory itself. return @rmdir($str); > > //call our function deleteAll('temporary_files');

The function above basically checks to see if the $str variable represents a path to a file. If it does represent a path to a file, it deletes the file using the function unlink.

However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one.

Finally, it removes the sub-directory itself by using PHP’s rmdir function.

Источник

Удаляет файл 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 );

Смотрите также

User Contributed Notes 12 notes

This will delete all files in a directory matching a pattern in one line of code.

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

$mask = «*.jpg»
array_map ( «unlink» , glob ( $mask ) );
?>

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:

// 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.

$old = getcwd (); // Save the current directory
chdir ( $path_to_file );
unlink ( $filename );
chdir ( $old ); // Restore the old working directory
?>

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.

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 ));
>
>
?>

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.

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.

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.

Источник

Удаление каталога с файлами в PHP

Удаление каталога с файлами в PHP

В предыдущей статье мы с Вами разбирали функции для работы с каталогами в PHP, и там я познакомил Вас с функцией rmdir(), которая удаляет каталог. Однако, я сказал, что таким способом получится удалить только пустую директорию, а вот как удалить каталог с файлами, Вы узнаете сейчас.

Принцип очень простой: чтобы удалить каталог с файлами, надо удалить сначала все файлы, а также все подкаталоги. Внутри подкаталогов могут быть также файлы и другие подкаталоги, их также надо очистить. В общем, сложность состоит в том, что глубина каталогов может быть очень большой. И очевидно, что напрашивается рекурсия — вызов функции внутри самой себя.

Несмотря на кажущуюся сложность алгоритма, реализация очень простая и прозрачная:

function removeDirectory($dir) if ($objs = glob($dir.»/*»)) foreach($objs as $obj) is_dir($obj) ? removeDirectory($obj) : unlink($obj);
>
>
rmdir($dir);
>
?>

Постараюсь объяснить понятным языком алгоритм работы данной функции. Первым делом мы получаем список всех файлов внутри заданной директории. Если их там нет, то сразу удаляем её. Если они есть, то начинаем по-очереди перебирать. Если элемент является файлом, то просто удаляем его (unlink($obj)). Если же это каталог, то вызываем вновь нашу функцию, передав этот каталог. Это и есть рекурсия: функция вызывает сама себя. После вызова функцией самой себя всё начинается заново, но уже с другой директорией. У ней также удаляются все файлы, а все её директории отправляются вновь в эту функцию. Когда все директории и файлы удалены, у нас удаляется уже пустой каталог.

Я Вам скажу так, данный алгоритм не столько полезен с точки зрения практики (не так часто приходится удалять каталоги с файлами в PHP), сколько полезен для развития Вашего мышления. Это очень простой алгоритм и решает он весьма и весьма сложную задачу. Поэтому учитесь составлять алгоритмы — это самое главное в любом языке программирования.

Создано 12.06.2011 14:22:23

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 8 ):

    Михаил подскажите как удалить в папке несколько файлов png. Я пол дня провел над этой задачей. Прошу подсказать ))) Очень нужно.

    Получаете список файлов из каталога и удаляете их в цикле через unlink().

    Михаил, читаю ваши уроки с самого начала и не смог обнаружить у вас пояснения двух знаков, и их применение — ? : ; Например тут is_dir($obj) ? removeDirectory($obj) : unlink($obj); И что такое is_dir()?

    Подобная запись является аналогом цикла if и оформляется по такой форме: Условие ? Выражение1 : Выражение2 Выражение1 выполнится если Условие истино, Выражение2 если ложно, т.е. else. Например: $x>=$y ? echo(«Икс больше либо равен игрику») : echo(Икс меньше игрика); равносильно if($x>=$y) < echo("Икс больше либо равен игрику"); >else

    А как быть если в директории лежит .htaccess?

    Источник

    Оцените статью