How to Delete a File in PHP
This article provides a straightforward guide on how to delete a file from a server’s file system using PHP. You will learn about the primary built-in function used for file deletion, how to implement best practices to avoid common errors, and how to handle file permissions.
Using the unlink() Function
The standard way to delete a file in PHP is by using the built-in
unlink() function. This function accepts the path to the
file as its main argument and returns true on success or
false on failure.
Here is the basic syntax:
$filename = 'example.txt';
if (unlink($filename)) {
echo "The file was successfully deleted.";
} else {
echo "The file could not be deleted.";
}Best Practice: Check if the File Exists First
Attempting to delete a file that does not exist will trigger a PHP
warning. To prevent this, you should always check if the file exists
using the file_exists() function before calling
unlink().
$file_path = 'uploads/image.png';
if (file_exists($file_path)) {
if (unlink($file_path)) {
echo "File deleted successfully.";
} else {
echo "Error: Unable to delete the file.";
}
} else {
echo "Error: File does not exist.";
}Handling Permissions
If the unlink() function fails even though the file
exists, it is usually due to a permission issue.
- Web Server Permissions: The web server user (such
as
www-dataorapache) must have write and execute permissions on both the file itself and the directory containing the file. - File Locks: If another process or script is currently reading or writing to the file, you may need to close those handles before you can successfully delete it.