How to delete a file using PHP ?
To delete a file by using PHP is very easy. Deleting a file means completely erase a file from a directory so that the file is no longer exist. PHP has an unlink() function that allows to delete a file. The PHP unlink() function takes two parameters $filename and $context.
Syntax:
unlink( $filename, $context );
Below programs illustrate the above approach:
Program 1: This program uses unlink() function to remove file from directory.
Suppose there is a file named as “gfg.txt”
<?php // PHP program to delete a file named gfg.txt // using unlike() function $file_pointer = "test.txt"; // Use unlink() function to delete a file if (!unlink($file_pointer)) { echo ("$file_pointer cannot be deleted due to an error"); } else { echo ("$file_pointer has been deleted"); } ?> |
Output:
gfg.txt has been deleted
Program 2: This program uses unlink() function to delete a file from folder after using some operation.
<?php // PHP program to delete a file named gfg.txt // using unlike() function $file_pointer = fopen('gfg.txt', 'w+'); // writing on a file named gfg.txt fwrite($file_pointer, 'A computer science portal for geeks!'); fclose($file_pointer); // Use unlink() function to delete a file if (!unlink($file_pointer)) { echo ("$file_pointer cannot be deleted due to an error"); } else { echo ("$file_pointer has been deleted"); } ?> |
Output:
Warning: unlink() expects parameter 1 to be a valid path, resource given in C:\xampp\htdocs\server.php on line 12 Resource id #3 cannot be deleted due to an error
Note: If the file does not exist then it will display an error.
Recommended Posts:
- Delete the array elements in JavaScript | delete vs splice
- JavaScript | WebAPI | File | File.size Property
- JavaScript | WebAPI | File | File.type Property
- JavaScript | WebAPI | File | File.name Property
- How to include a JavaScript file in another JavaScript file ?
- How to delete last element from a map in C++
- Map.delete() In JavaScript
- PHP | MySQL Delete Query
- Delete first character of a string in JavaScript
- How to delete an array element based on key in PHP?
- MongoDB | Delete Database using MongoShell
- If we delete cookies of a site, we can still logged in without logging again
- PHP | Program to delete an element from array using unset() function
- How to recursively delete a directory and its entire contents (files + sub dirs) in PHP?
- robots.txt File
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



