How to Delete a File in PHP: Simple Guide with Examples
To delete a file in PHP, use the
unlink() function with the file path as its argument. This function removes the specified file from the server if it exists and the script has permission to delete it.Syntax
The unlink() function deletes a file from the filesystem. It takes one parameter:
- filename: The path to the file you want to delete.
If the file is deleted successfully, unlink() returns true. Otherwise, it returns false.
php
bool unlink ( string $filename )
Example
This example shows how to delete a file named example.txt in the same directory as the script. It checks if the file exists before trying to delete it and prints a message based on success or failure.
php
<?php $filename = 'example.txt'; if (file_exists($filename)) { if (unlink($filename)) { echo "File '$filename' was deleted successfully."; } else { echo "Could not delete the file '$filename'."; } } else { echo "File '$filename' does not exist."; } ?>
Output
File 'example.txt' was deleted successfully.
Common Pitfalls
Common mistakes when deleting files in PHP include:
- Trying to delete a file that does not exist, which causes
unlink()to fail. - Not having the correct permissions to delete the file, leading to failure.
- Using incorrect file paths, especially relative paths that do not point to the intended file.
Always check if the file exists and handle errors gracefully.
php
<?php // Wrong way: no check if file exists if (unlink('missing.txt')) { echo "Deleted."; } else { echo "Failed to delete."; } // Right way: check file existence first if (file_exists('missing.txt')) { if (unlink('missing.txt')) { echo "Deleted."; } else { echo "Failed to delete."; } } else { echo "File does not exist."; } ?>
Output
Failed to delete.File does not exist.
Quick Reference
Remember these tips when deleting files in PHP:
- Use
unlink()to delete files. - Check file existence with
file_exists()before deleting. - Ensure your script has permission to delete the file.
- Use correct and absolute file paths to avoid mistakes.
Key Takeaways
Use the unlink() function with the file path to delete a file in PHP.
Always check if the file exists using file_exists() before deleting.
Ensure your PHP script has permission to delete the target file.
Use correct file paths to avoid deleting the wrong file or failing.
Handle errors gracefully to inform if deletion was successful or not.