Deleting Files

This section describes how to use PHP to delete files on Windows systems.

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) - deletes the file defined by the first parameter. The function returns a true or false value.

The following example demonstrates how to delete a file using the unlink() function:

filedelete.php

<?php

$filename = "C:/Documents and Settings/Administrator/MyFiles/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 = "C:/Documents and Settings/Administrators/MyFiles/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";