unlink(): To delete a File

$path="images/all11.css";
if(unlink($path)) {
echo "Deleted file ";
}
File Delete 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.

Here is the syntax.
unlink($path);

Example: Validating File Existence Before Deletion

We can check the path by using file_exists function to know if file is available for deletion.
$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.
We have used if condition to check whether the file delete command is successful or not. But the command below will not work.
$path="https://domainname/file/red.jpg";
if(unlink($path)) echo "Deleted file ";
The warning message will say unlink() [function.unlink]: HTTP does not allow unlinking.

We can suppress the warning message by adding a @ symbol before the unlink command .
Based on the success of the file delete command we can further execute our code by using if else code block.
$path="test.html";
if(@unlink($path)) {echo "Deleted file "; }
else{echo "File can't be deleted";}
Here we are deleting one file only.

Example: Recursive File Deletion in Directories

We can also delete all the files of a directory or selected files by using PHP.
function deleteFilesInDir($dir) {
    foreach(glob($dir.'/*') as $file) {
        if (is_dir($file)) {
            deleteFilesInDir($file);
        } else {
            unlink($file);
        }
    }
}
deleteFilesInDir('test_dir');
Deleting database record linked to file.
The name of the file is stored in a table record. While deleting such file , first record is to be deleted ( if required ) and on success of deletion the respective file is to be deleted.

Deleting record with image from MySQL table

File Deleting all ( or by selection ) files of a directory Directory Functions
PHP
Subscribe to our YouTube Channel here



plus2net.com







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()




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer