Нередко, при создании программы, возникает необходимость удаления файлов (причины могут быть самыми разными) и в этом случае нам на помощь приходит unlink php. Сегодня мы научимся удалять файлы в PHP и рассмотрим несколько примеров.
Удаляем файлы при помощи unlink PHP
Для удаления файлов служит функция unlink() . Синтаксис у этой функции следующий:
unlink (имя_файла)
Данная функция является логической и поэтому в случае успешного удаления файла возвращает TRUE, а в случае неудачи – FALSE. Рассмотрим использование unlink() на примере:
Следует заметить, что при повторной загрузке данной страницы программа выдаст ошибку. Связанно это с тем, что при первом вызове функции она уже удалила файл и в следующий раз не может его обнаружить.
Существует несколько путей решения данной проблемы. Например можно использовать более сложную внутреннюю архитектуру программы, использовав условные операторы if . Или достаточно поставить символ @ перед самой функцией для игнорирования возникающих ошибок. В этом случае, даже если файл не будет обнаружен, ошибка не будет инициирована:
Удалять файлы в PHP при помощи unlink совсем не сложно, как говорится, ломать — не строить. В следующий раз мы научимся проверять состояние файлов.
Продолжаем урок, который посвящен теме «Работа с файлами PHP
». Если вы не читали предыдущий , рекомендую почитать, а те, кто читал, двигаемся дальше. В этом уроке вы научитесь удалять созданный или существующий файл с помощью PHP, копировать или переименовывать, блокировать файл.
Ну что, если вы готовы, тогда в бой…
Удаление файла на PHP
Если вам нужно удалить какой-либо файл, воспользуйтесь PHP-функцией unlink() :
Unlink(имя_файла);
Имя_файла – здесь укажите имя файла, который нужно удалить.
Припустим, нам нужно удалить файл «file.txt », пример для заполнения будет вот такой:
Unlink("file.txt");
Готовый код: