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.
Interview Questions & Answers
What is include() function in PHP?
Can we include a file two times in any PHP page?
Which is the PHP function to delete a file from server?
What is fopen function PHP?
What is the difference between unlink() and unset() in PHP?
How to check if a file exists in PHP?
How to get the size of a file in PHP?