Delete Uploaded Files from Folder using PHP and MySQL

Hello friends, this is ours continuation post of previous how to upload and view files, now In this tutorial we will see that how to completely delete(remove) uploaded files from folder as well as from MySQL database table using PHP, you can delete any files pdf, mp3, image, video etc. when you upload any file it moves on particular folder and it’s necessary to update or delete files from folder as well when you delete data from mysql. so let’s have a look at this simple yet useful tutorial.

Delete Uploaded Files From Folder using PHP and MySQL

Read Also : Upload Insert, Update & Delete operations with Image [PDO Query]

Here i am going to use the same old Database and table with dumping data which have been used in ours file uploading tutorial.

In PHP using unlink() function we can delete files from folder.

example :

unlink("folder_name/".file_name);

Sample Code :


$res=mysql_query("SELECT file FROM tbl_uploads WHERE id=".$_GET['remove_id']);
$row=mysql_fetch_array($res);
mysql_query("DELETE FROM tbl_uploads WHERE id=".$_GET['remove_id']);
unlink("uploads/".$row['file']);

Script explained :
– First write select query to fetch file from database.
– This code can be work with if(isset($_GET[]) condition.
– After fetching file put the fetched file into the unlink() function like above.

That’s it guys, hope you like this short and simple tutorial.