Cover Image for PHP Delete File
224 views

PHP Delete File

To delete a file in PHP, you can use the unlink() function. The unlink() function is used to delete a file from the server’s filesystem. Make sure you have the necessary permissions to delete the file, as the function will not work if the file is write-protected or if the directory does not have the proper permissions.

Here’s a simple example of how to use the unlink() function to delete a file:

$fileToDelete = "path/to/your/file.txt"; // Replace this with the actual path of the file you want to delete.

if (file_exists($fileToDelete)) {
    if (unlink($fileToDelete)) {
        echo "File deleted successfully.";
    } else {
        echo "Error deleting the file.";
    }
} else {
    echo "File not found.";
}

In this example, we first check if the file exists using file_exists() to avoid trying to delete a non-existent file. If the file exists, we attempt to delete it using unlink(). The function returns true if the file is deleted successfully and false if there is an error.

Please exercise caution when using the unlink() function, as deleting a file is a permanent action, and there is no way to recover the file once it is deleted. Always double-check that you are deleting the correct file and have appropriate backup measures in place if necessary.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS