Как удалить файл в PHP? Unlink php — удаление файлов Как это все работает.

Продолжаем урок, который посвящен теме «Работа с файлами PHP ». Если вы не читали предыдущий , рекомендую почитать, а те, кто читал, двигаемся дальше. В этом уроке вы научитесь удалять созданный или существующий файл с помощью PHP, копировать или переименовывать, блокировать файл.
Ну что, если вы готовы, тогда в бой…

Удаление файла на PHP

Если вам нужно удалить какой-либо файл, воспользуйтесь PHP-функцией unlink() :

Unlink(имя_файла);

Имя_файла – здесь укажите имя файла, который нужно удалить.

Припустим, нам нужно удалить файл «file.txt », пример для заполнения будет вот такой:

Unlink("file.txt");

Готовый код:

Если файл «file.txt » присутствовал, скрипт его удален.

Копирование файла на PHP

Если вам нужно из одного файла перекопировать содержимое в другой файл, воспользуйтесь PHP-функцией copy() .

Copy("файл1", "файл2");

Файл1 – имя файла откуда будет копироваться текст
- файл2 – имя файла куда будет копироваться текст

Для примера создайте на локальном сервере в папке «test-1 » файл под названием «file2.txt ». Пусть файл будет пустым. Теперь вставим этот код copy("file.txt", "file2.txt"); в php код «file.php »:

Что мы сделали? Создали через PHP файл под названием «file.txt », сделали запись в файле «file.txt » через PHP « Я рад видеть вас на блоге сайт », вывели результат в браузере, скопировали текст с файла «file.txt » и вставили в файл «file2.txt ». Не верите, что так все произошло? Вы помните, что файл «file2.txt » был пустым?! Откройте его! И что вы видите? Да, правильно, текст, который был в файле «file.txt »:

Переименование файла на PHP

Чтобы сделать переименование файла, воспользуйтесь PHP-функцией rename() :

Rename("файл1", "файл2");

Файл1 – название файла, которое нужно заменить (переименовать )
- файл2 – здесь нужно дать новое название файла

Пример для заполнения вот такой:

Rename("file2..txt");

Вот готовый код:

Файл «file2.txt » переименован в файл «сайт.txt ».

На этом, я думаю, следует закончить наш урок. Но это еще не все, в следующем уроке продолжим работу с файлами.

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

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

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

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

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

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

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

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

14 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 );
}

?>

10 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
?>

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

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

11 years ago

Ggarciaa"s post above has already one small error, closedir has to be used even if $DeleteMe is false











}

Closedir ($dh );
if ($DeleteMe ){
@ rmdir ($dir );
}
}

?>

9 months ago

Handling "Resource Unavailable" error by unlink() as Exception using try catch

Even is_file() or file_exists() will check for file is exists or not, there are chances that file is being used by some applications that will prevent deletion and unlink() will display "Resource Unavailable" error.

So after trying many methods like: `is_resource()`, `is_writable()`, `stream_get_meta_data()`...etc, I reached the only best way to handle error while *"deleting"* a file that is either **not exists** or **is exists but being used by some application**

function delete_file($pFilename)
{
if (file_exists($pFilename)) {
// Added by muhammad.begawala
// "@" will stop displaying "Resource Unavailable" error because of file is open some where.
// "unlink($pFilename) !== true" will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if(@unlink($pFilename) !== true)
throw new Exception("Could not delete file: " . $pFilename . " Please close all applications that are using it.");
}
return true;
}

/* === USAGE === */

try {
if(delete_file("hello_world.xlsx") === true)
echo "File Deleted";
}
catch (Exception $e) {
echo $e->getMessage(); // will print Exception message defined above.
}

11 years ago

Ggarciaa"s post above has one small error, it will ignore file and directory strings that are evaluated as false (ie. "0")

Fixed code is below (false !==)

// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone

Function SureRemoveDir ($dir , $DeleteMe ) {
if(! $dh = @ opendir ($dir )) return;
while (false !== ($obj = readdir ($dh ))) {
if($obj == "." || $obj == ".." ) continue;
if (!@ unlink ($dir . "/" . $obj )) SureRemoveDir ($dir . "/" . $obj , true );
}
if ($DeleteMe ){
closedir ($dh );
@ rmdir ($dir );
}
}

//SureRemoveDir("EmptyMe", false);
//SureRemoveDir("RemoveMe", true);

?>

8 years ago

Unlink can fail after using ODBC commands on the file (on Windows).

Neither nor did the trick.

Only released the file such that it could be deleted afterwards ...

PHP - язык программирования, в основном используемый для создания динамических web-страниц. Равно как и любой другой язык программирования, PHP содержит массу возможностей, среди которых очень много полезных. К примеру, возможность удаления файла, которую вы можете использовать в ваших скриптах.

Этот совет поможет вам узнать, как удалить файл в PHP при помощи функции unlink .

Пошаговая инструкция:

Для удаления файла в PHP можно использовать функцию unlink . На примере простого скрипта, разберем работу unlink :

  1. Создайте текстовый файл в текстовом редакторе (vi/vim, nano, gedit или просто в стандартном Блокноте).
  2. Наберите или просто скопируйте в него следующий код: $file="example.log";
    unlink($file);
    ?>
  3. Сохраните (к примеру под именем testunlink.php) и разместите созданный файл скрипта на вашем тестовом web-сервере. В этом же каталоге создайте файл example.log с любым содержимым. Именно его мы и будем удалять.
  4. Запустите скрипт, вызвав его в браузере, и, посмотрев вновь в каталог, вы обнаружите, что файла example.log там больше нет. Unlink сделал свое дело!

Как это все работает:

Первая строка кода скрипта: определяем тип нашего скрипта.

Вторая строка кода: После запуска созданного нами скрипта, переменной file будет присвоено значение example.log (обратите внимание, что файл с одноименным названием должен присутствовать в том же каталоге, что и созданный нами скрипт. Просто создайте его с любым содержимым!).

Третья строка кода: Удаляем файл example.log, передав его в качестве аргумента функции unlink.

Четвертая строка кода скрипта: конец кода php.



 

Возможно, будет полезно почитать: