Deleting Files
PHP includes the unlink() function for deleting files. The unlink() function should be used with caution. Once a file is deleted, it cannot be retrieved. The function is defined below:
unlink($filename)
The following example demonstrates how to delete a file using the unlink() function:
filedelete.php
<?php
$filename = "myfile.txt";
$status = unlink($filename) or exit("Could not delete the file");
echo "file deleted successfully";
?>
The first step is to create a variable to hold the full path to the file whose contents will be deleted:
$filename = "myfile.txt";
The unlink() function is executed, accepting one parameter, the path of the original file - $filename. The unlink() function returns a value of TRUE if the file is deleted successfully;otherwise a value of FALSE is returned. The returned value is stored in the variable $status.
$status = unlink($filename) or die("Could not delete file");
If the unlink() function fails, the exit() function executes displaying an error message. Otherwise, a success message is displayed using the echo statement.
echo "file deleted successfully";