How To Delete File From Folder In PHP?
May 01, 2021 . Admin
Hello Friends,
In this post, we will learn How To Delete a File Using PHP To delete a file by using PHP is very simple. Deleting a file means completely erase(remove) 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)Example : 1
This program uses unlink() function to remove file from directory. Suppose there is a file named as “demo.txt”.
<?php // PHP program to delete a file named demo.txt // using unlike() function $file_name = "demo.txt"; // Use unlink() function to delete a file if (!unlink($file_name)) { echo ("$file_name cannot be deleted due to an error"); } else { echo ("$file_name has been deleted"); } ?>Output:
demo.txt has been deletedExample : 2
This program uses unlink() function to delete a file from folder after using some operation.
<?php // PHP program to delete a file named demo.txt // using unlike() function $file_name = fopen('demo.txt', 'w+'); // writing on a file named demo.txt fwrite($file_name, 'Hi, welcome to Mywebtuts.com!'); fclose($file_name); // Use unlink() function to delete a file if (!unlink($file_name)) { echo ("$file_name cannot be deleted due to an error"); } else { echo ("$file_name has been deleted"); } ?>Output:
Warning: unlink() expects parameter 1 to be a valid path, resource given in /var/www/html/php_learn/php_blogs/unlink.php on line 12 Resource id #3 cannot be deleted due to an error
I Hope It Will Help You...