Php удалить файлы по маске

Обновлено: 04.07.2024

Ум за разумом.
Есть директория upload, в ней есть разные файлы. При выводе списка файлов, на против каждого должна быть кнопочка удалить и файл должен удаляться из директории.
По идее это делает unlink но у меня ни как не получается(

__________________
Помощь в написании контрольных, курсовых и дипломных работ здесь

Удаление файла из директории
Вообщем такое дело, есть простой скрипт галереи на PHP, всё работает прекрасно, но увы, никак не.

Удаление файла из директории
Здравствуйте форумчане, есть одна проблема! у меня есть скрипт вывода изображений на экран, все.

Удаление директории со всем содержимым.
Такой команды в пхп нет. Однако использовать exec('..'); не хочется -- получается.

Удаление файлов внутри директории по маске
удаление файлов зная директорию и не точную названию. Например@unlink($this->root_dir .

Да опечатка, включая название темы. Но сути не меняет. Данный скрипт удаляет все файлы из директории, что печально. Нужно что бы была кнопка которая удаляла бы по одному файлу, напротив которого она находится. выводите чекбоксы рядом, и уже по ним определяйте, какой нужно удалить Можете через ajax попробовать реализовать, красиво получится)

ТСу: разделите логику и представление на 2 файла, не надо этих

. Почитайте про стандарты форматирования кода.
P.S.Может мне кто-нибудь обьяснить, зачем это:
Он что, на каждой итерации пытается удалить директорию, в которой файлы лежат? Или я еще не проснулся? 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. С мануалами я ознакомился в первую очередь. Интересная идея с чекбоксами) можно поподробней расписать?) Не работает увы код( Все время выходит в неверное имя файла(

и что? У вас есть файлы с названиями 'foo', 'bar', 'lol' ?

Добавлено через 1 минуту

зачем загонять в массив, да еще и который используется выше!?

Удаление директории при нажатии на кнопку Удалить
Всем привет!Есть текстовое поле и кнопка!В поле вводим имя папки(директории) и жмём на кнопку и.


Удаление изображения из директории вместе с записью из бд mysql
есть таблица с столбцами id, title, image. в столбце image названия картинок (jyyk.jpg например).

Создание файла в отдельной директории
У меня есть папка /task , в которой лежит код. Этим кодом надо создать страницу в корне или папке.

Скачивание файла из другой директории!
Здравствуйте. В общем, у меня есть скрипт чтения файлов и вывода в список, также их можно скачать.

Пытается удалить директорию с именем directory . Директория должна быть пустой и должны иметься необходимые для этого права. При неудачном выполнении будет сгенерирована ошибка уровня E_WARNING .

Список параметров

Путь к директории.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

<?php
if (! is_dir ( 'examples' )) mkdir ( 'examples' );
>

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

  • is_dir() - Определяет, является ли имя файла директорией
  • mkdir() - Создаёт директорию
  • unlink() - Удаляет файл

User Contributed Notes 29 notes

Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

<?php
public static function delTree ( $dir ) <
$files = array_diff ( scandir ( $dir ), array( '.' , '..' ));
foreach ( $files as $file ) <
( is_dir ( " $dir / $file " )) ? delTree ( " $dir / $file " ) : unlink ( " $dir / $file " );
>
return rmdir ( $dir );
>
?>

Never ever use jurchiks101 at gmail dot com code. It contains command injection vulnerability.
If you want to do it that way, use something like this instead:

<?php
if ( PHP_OS === 'Windows' )
exec ( sprintf ( "rd /s /q %s" , escapeshellarg ( $path )));
>
else
exec ( sprintf ( "rm -rf %s" , escapeshellarg ( $path )));
>
?>

Note the escapeshellarg usage to escape any possible unwanted character, this avoids putting commands in $path variable so the possibility of someone "pwning" the server with this code

some implementations of recursive folder delete don't work so well (some give warnings, other don't delete hidden files etc).

this one is working fine:
<?php

function rrmdir ( $src ) $dir = opendir ( $src );
while( false !== ( $file = readdir ( $dir )) ) if (( $file != '.' ) && ( $file != '..' )) $full = $src . '/' . $file ;
if ( is_dir ( $full ) ) rrmdir ( $full );
>
else unlink ( $full );
>
>
>
closedir ( $dir );
rmdir ( $src );
>

The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy.

itay at itgoldman's function falls into an infinite loop if the $src directory doesn't exist.
Here's a fix - one should do at least a file_exists() check before the loop:

function rrmdir($src) if (file_exists($src)) $dir = opendir($src);
while (false !== ($file = readdir($dir))) if (($file != '.') && ($file != '..')) $full = $src . '/' . $file;
if (is_dir($full)) rrmdir($full);
> else unlink($full);
>
>
>
closedir($dir);
rmdir($src);
>
>

Thanks to itay for the original function, though, it was helpful.

Say, you're working on Windows and continue to get a permission's error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can't find that program, the line

<?php closedir ( opendir ( $dirname )); ?>

may solve the problem!
Make sure to write this before rmdir($dirname);.

I was working on some Dataoperation, and just wanted to share an OOP method with you.

It just removes any contents of a Directory but not the target Directory itself! Its really nice if you want to clean a BackupDirectory or Log.

Also you can test on it if something went wrong or if it just done its Work!

I have it in a FileHandler class for example, enjoy!

public function deleteContent ( $path ) try $iterator = new DirectoryIterator ( $path );
foreach ( $iterator as $fileinfo ) if( $fileinfo -> isDot ())continue;
if( $fileinfo -> isDir ()) if( deleteContent ( $fileinfo -> getPathname ()))
@ rmdir ( $fileinfo -> getPathname ());
>
if( $fileinfo -> isFile ()) @ unlink ( $fileinfo -> getPathname ());
>
>
> catch ( Exception $e ) // write log
return false ;
>
return true ;
>

Another simple way to recursively delete a directory that is not empty:

<?php
function rrmdir ( $dir ) <
if ( is_dir ( $dir )) <
$objects = scandir ( $dir );
foreach ( $objects as $object ) <
if ( $object != "." && $object != ".." ) <
if ( filetype ( $dir . "/" . $object ) == "dir" ) rrmdir ( $dir . "/" . $object ); else unlink ( $dir . "/" . $object );
>
>
reset ( $objects );
rmdir ( $dir );
>
>
?>

I also ran into the permissions issue in Windows when deleting a folder and the solution was to close all editors which had files opened which were located in the folder structure.

This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get "stuck" and throw permissions errors. I was not able to delete them with PHP or in windows itself. The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own. Disabling the wincachce module resolved the issue.

Hope this helps.

function unlinkDir($dir)
$dirs = array($dir);
$files = array() ;
for($i=0;;$i++)
if(isset($dirs[$i]))
$dir = $dirs[$i];
else
break ;

if($openDir = opendir($dir))
while($readDir = @readdir($openDir))
if($readDir != "." && $readDir != "..")

foreach($files as $file)
unlink($file) ;

>
$dirs = array_reverse($dirs) ;
foreach($dirs as $dir)
rmdir($dir) ;
>

it Will Delete All Fildes in folder and that folder too.

echo $path = 'D:\xampp\htdocs\New folder\New folder';

function rmdir_recursive($dir) $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($it as $file) if ($file->isDir()) rmdir($file->getPathname());
else unlink($file->getPathname());
>
rmdir($dir);
>
rmdir_recursive($path);

It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links.

<?php
public static function delTree ( $dir ) <
$files = array_diff ( scandir ( $dir ), array( '.' , '..' ));
foreach ( $files as $file ) <
( is_dir ( " $dir / $file " ) && ! is_link ( $dir )) ? delTree ( " $dir / $file " ) : unlink ( " $dir / $file " );
>
return rmdir ( $dir );
>
?>

Keep in mind that if you know what your host OS is, you can always just call the appropriate system call using exec() or the like. For example:

exec('rmdir folder-to-delete /s /q'); //windows
exec('rmdir -rf folder-to-delete'); //OS X/*nix?

I've noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO. if you get a permissions error and there shouldn't be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.

while ($contents = readdir($directoryHandle))

if a folder named 0 (zero) is found during traversing the hierarchy

A patch to previous script to make sure rights for deletion is set:

<?php
//Delete folder function
function deleteDirectory ( $dir ) <
if (! file_exists ( $dir )) return true ;
if (! is_dir ( $dir ) || is_link ( $dir )) return unlink ( $dir );
foreach ( scandir ( $dir ) as $item ) <
if ( $item == '.' || $item == '..' ) continue;
if (! deleteDirectory ( $dir . "/" . $item )) <
chmod ( $dir . "/" . $item , 0777 );
if (! deleteDirectory ( $dir . "/" . $item )) return false ;
>;
>
return rmdir ( $dir );
>
?>

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]

Works fine, tested on PHP 5.4(EasyPHP server)
function deletedir($dir)
if (is_dir($dir))
<
$files = scandir($dir);
foreach ($files as $file)
<
if ($file != "." && $file != "..")
<
if (filetype($dir."/".$file) == "dir")
$this->deletedir($dir."/".$file);
>
else
unlink($dir."/".$file);
>
>
>
reset($objects);
if(rmdir($dir))
return 'deleted successfully!';
>
else
return 'delete failed!';
>
>
else
return 'doesn\'t exist or inaccessible!';
>
>
Something to note:
You have to take care of file permission if necessary Sometimes you would face situations in which rmdir($dirname) would give "permission denied" errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir('dirr'); then change the permissions of the folder that contains 'dirr'. In case you're trying to rmdir() and you keep getting 'Permission denied' errors, make sure you don't have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().

if you get this problem Permission denied in windows testing your site maybe this will resolve the problem

<?php
if( file_exists ( $path . '/Thumbs.db' )) <
unlink ( $path . '/Thumbs.db' );
>
?>

and then

I wasn't having much luck with the recursive delete functions below, so I wrote my own:

<?php
// ensure $dir ends with a slash
function delTree ( $dir ) <
$files = glob ( $dir . '*' , GLOB_MARK );
foreach( $files as $file ) <
if( substr ( $file , - 1 ) == '/' )
delTree ( $file );
else
unlink ( $file );
>
rmdir ( $dir );
>
?>

Simple. Works.

This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

<?php
function deleteAll ( $directory , $empty = false ) <
if( substr ( $directory ,- 1 ) == "/" ) <
$directory = substr ( $directory , 0 ,- 1 );
>

if(! file_exists ( $directory ) || ! is_dir ( $directory )) <
return false ;
> elseif(! is_readable ( $directory )) <
return false ;
> else <
$directoryHandle = opendir ( $directory );

while ( $contents = readdir ( $directoryHandle )) <
if( $contents != '.' && $contents != '..' ) <
$path = $directory . "/" . $contents ;

if( is_dir ( $path )) <
deleteAll ( $path );
> else <
unlink ( $path );
>
>
>

if( $empty == false ) <
if(! rmdir ( $directory )) <
return false ;
>
>

// Recursive PHP function to completely remove a directory

function delete_directory_recursively( $path )

$dir = new \DirectoryIterator( $path );

// Iterate through the subdirectories / files of the provided directory
foreach ( $dir as $dir_info )

// Exclude the . (current directory) and .. (parent directory) paths
// from the directory iteration
if ( ! $dir_info->isDot() )

// Get the full currently iterated path
$iterated_path = $dir_info->getPathname();

// If the currently iterated path is a directory
if ( $dir_info->isDir() )

// which is not empty (in which case scandir returns an array of not 2 (. and ..) elements)
if ( count( scandir( $iterated_path ) ) !== 2 )

// Call the function recursively
self::remove_directory_recursively( $iterated_path );

// if the currently iterated path is an empty directory, remove it
rmdir( $iterated_path );

// If the currently iterated path describes a file, we need to
// delete that file
unlink( $iterated_path );

> // loop which opens if the currently iterated directory is neither . nor ..

> // end of iteration through directories / files of provided path

// After iterating through the subpaths of the provided path, remove the
// concerned path
rmdir( $path );

> // end of delete_directory_recursively() function definition

Concise way to recursively remove a directory:

I had situation where the rmdir was returning warning message as within last loop it was already removed. So here is quick fix by adding is_dir to the DelTree routine below

<?php
function delTree ( $dir ) <
$files = glob ( $dir . '*' , GLOB_MARK );
foreach( $files as $file ) <
if( substr ( $file , - 1 ) == '/' )
delTree ( $file );
else
unlink ( $file );
>

У меня большое количество посетителей в день и создаётся до 50 тысяч сессий в день. Пишу скрипт, чтобы когда число сессий в папке mod-tmp превысит 20 тысяч, сервер удалял бы из неё все файлы и перезагружался. Помогите, пожалуйста, как с помощью PHP удалить все файлы из 1 папки?


8,768 10 10 золотых знаков 26 26 серебряных знаков 54 54 бронзовых знака 161 1 1 золотой знак 2 2 серебряных знака 17 17 бронзовых знаков Вроде как нельзя удалить сразу все. Можно получить список и удалить в цикле, но это долго. Можно попробовать через exec запускать внешнюю программу. Или вообще написать демона который будет работать выше чем пхп и быстрее Довольно интересный я бы сказал не вопрос а ситуация. Копайте в торону cron php > чтобы когда число сессий в папке mod-tmp привышало 20 тысяч сервер удалял из неё все файлы и перезагружался Простите, но это форменный кошмар, других слов я просто не нахожу. Во-первых, PHP сам чистит протухшие сессии, если не менялись настройки session.gc-* А во-вторых, вас не волнует, что пользователей будет постоянно выкидывать с сайта, не говоря уже о неработоспособности сайта во время перезагрузки?

Вот самый быстрый и лёгкий способ:

Дальше вызываете где и когда нужно. К примеру, если это Wordpress, вешаете add_action('save_post','clear') .


6,920 5 5 золотых знаков 24 24 серебряных знака 64 64 бронзовых знака

Удалить средствами php сразу все не получится. Только в цикле. Возможно следует посмотреть в сторону демонов, как сказал @Inart.
Код для пхп:


6,920 5 5 золотых знаков 24 24 серебряных знака 64 64 бронзовых знака 3,766 16 16 серебряных знаков 24 24 бронзовых знака

Грубый подход, очень грубый:

Это сработает только в Linux. Еще раз скажу, подход очень грубый и лучше такого не использовать НИКОГДА.


6,920 5 5 золотых знаков 24 24 серебряных знака 64 64 бронзовых знака 1,208 1 1 золотой знак 9 9 серебряных знаков 23 23 бронзовых знака

Вероятно, всё намного проще. ISPManager криво меняет конфиг php отключая сборщик мусора сессий.

Открывайте конфиг php. По-дефолту /etc/php.d/apache/php.ini

Меняйте параметр session.gc_probability=0 в значение 1

Перезапускаете аппач /etc/init.d/apache2 restart

Всё, сборка мусора снова — дело php.



А попробуйте лучше удалять не все сразу, а постепенно. То есть PHP-скрипт каждого пользователя, который зашел к вам на сайт, будет удалять, например, по 1000 файлов, пока их не останется вовсе. Это сделать не сложно. Достаточно одного XML-Файла ( БД здесь не обязательно использовать) с двумя записями - сколько осталось и вторая - надо ли производить удаление.

Читайте также: