unlink() removes a file when PHP has permission to do so. Check that the target is a real file first and avoid building deletion paths directly from untrusted user input.
$file = __DIR__ . '/uploads/old-file.txt';
if (is_file($file)) {
if (!unlink($file)) {
echo 'The file could not be deleted.';
}
}The examples below show additional variations and practical file-handling cases.
$path="images/all11.css";
if(unlink($path)) {
echo "Deleted file ";
}
We can delete files by giving its URL or path in PHP by using unlink command. This command will work only if write permission is given to the folder or file. Without this the delete command will fail. unlink($path);
$file = 'example.txt';
if (file_exists($file)) {
if (unlink($file)) {
echo "File deleted successfully.";
} else {
echo "Error deleting the file.";
}
} else {
echo "File does not exist.";
}
Here $path is the relative path of the file calculated from the script execution. $path="https://domainname/file/red.jpg";
if(unlink($path)) echo "Deleted file ";
unlink() is for filesystem paths. Do not pass remote HTTP/HTTPS URLs to it.
@). Check the target first and handle a failed deletion explicitly.
$path = __DIR__ . '/test.html';
if (is_file($path) && unlink($path)) {
echo 'Deleted file';
} else {
echo 'File was not deleted';
}
Here we are deleting one file only.
function deleteFilesInDir($dir) {
foreach(glob($dir.'/*') as $file) {
if (is_dir($file)) {
deleteFilesInDir($file);
} else {
unlink($file);
}
}
}
deleteFilesInDir('test_dir');
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| hariv21 | 31-03-2010 |
| nice | |
| php | 29-09-2012 |
| amazing tutorils.... thanks | |
| bell | 16-07-2014 |
| how to generate a Multiple deletion method | |
| jamroz | 16-09-2014 |
| sir i make a page which delete a record but a file or image that are stored in the folder did not removed . How to remove from folder a picture using unlink() | |