Deleting a file in PHP is done using the built-in unlink() function. This function permanently removes a file from the server, so it should be used with caution. It is commonly used in file management systems, admin dashboards, and upload/delete functionalities.
Syntax of unlink()
unlink(string $filename);
Parameter
- $filename — The name or path of the file to delete.
Return Value
- Returns true on successful deletion.
- Returns false if deletion fails.
Basic Example: Deleting a File
<?php
$file = "old-data.txt";
if (unlink($file)) {
echo "File deleted successfully!";
} else {
echo "Error: Could not delete the file.";
}
?>
Example: Deleting a File from a Directory
<?php
$filePath = "uploads/temp-image.jpg";
if (file_exists($filePath)) {
if (unlink($filePath)) {
echo "File removed from directory.";
} else {
echo "Unable to delete the file.";
}
} else {
echo "File does not exist.";
}
?>
Checking if a File Exists Before Deleting
It is always recommended to verify the file’s existence:
if (file_exists("notes.txt")) {
unlink("notes.txt");
} else {
echo "File not found.";
}
This helps avoid errors or warnings on the server.
Common Reasons unlink() Fails
1. File Permissions
The file or directory may not allow deletion (CHMOD issue).
2. Incorrect File Path
Always double-check folder structure and file names.
3. File in Use
Some server processes may temporarily lock a file.
4. Trying to Delete a Directory
unlink() only deletes files — not folders.
To delete a directory, rmdir() must be used.
Security Tips When Deleting Files
Always validate filenames
Never delete files directly based on user input without sanitizing.
Avoid absolute user-provided paths
Prevent users from deleting system files using path traversal attacks.
Use a restricted directory
Store deletable files inside a controlled folder like /uploads/.
Practical Use Cases
Deleting user-uploaded images
When a user changes their profile picture, old images can be deleted.
Removing temporary files
Delete files created during processing once they are no longer needed.
Cleaning backup logs automatically
Cron jobs often delete old log files using unlink().
Output Example
Before: /uploads/user123.png
After: File successfully deleted from the server.
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/