How To Delete File Or Remove File Using PHP Examples
When working with files in PHP, there may be a necessity to create files dynamically and at the same time, remove file or delete file using PHP. In this article, I am going to share a very easy way to delete a file using PHP. The actual code is just 1 line, so it’s super easy to follow.
Examples On How To Remove File Or Delete File Using PHP
To do this, we simply use the “unlink” function. So what unlink simply does is it “Deletes a file”. That’s it! Nothing more!
Command:
unlink( $filename );
Example: Using PHP to delete a file with the help of unlink function
In this example, I am going to first create a sample test file and then once it is created in the following steps, I will delete the file using PHP.
<?php $temp_file_name = tempnam ('tmp/', "Test"); if( $temp_file_name ) { echo 'File successfully CREATED.<br />'; } else { echo 'Unable to CREATE file.<br />'; } $fp = fopen($temp_file_name, "w"); fwrite($fp, 'Some sample content'); fclose($fp); $delete_result = unlink($temp_file_name); if( $delete_result ) { echo 'File successfully DELETED.<br />'; } else { echo 'Unable to DELETE the file.<br />'; } ?>
If you have tried the demo, you will notice that first, the file is created & in the succeeding step, the file is deleted. If you have not yet tried the demo, then do it by clicking the button below.
Your Turn!
Do you know of any other ways of using PHP to delete file or remove a file? Feel free to suggest by commenting below.