Which is the PHP function to delete a file from server?
Use the unlink() function. It deletes a file from the server and returns true on success. It is better to check first if the file exists.
<?php
$file = "sample-file.txt";
if (file_exists($file) && unlink($file)) {
echo "File deleted";
} else {
echo "File not found or could not be deleted";
}
?>
Output:
Tutorials Class - Output Window
File deleted
- The deleted file can not be taken back.
- PHP needs permission to delete the file, otherwise you get a warning.
- Never pass a file name from user input without checking it.
- Do not mix it with
unset(), see unlink() vs unset().
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Advanced |
| PHP File Upload |
| PHP File Handling |
| PHP File Inclusion |
| Exercises & Assignments |
|---|
| No Content Found. |