Jump to content

unlink to delete 1 or more files and not ALL files !!


Skylight_lady

Recommended Posts

Hi Guys, here is a problem i have with deleting a file(s) via a cron job. Now i have written a code which deleted all files in a directory .... but it's not what i want. i want to delete one or more files that all have the same value in the database table with an value of delete eg:

 

$query = "SELECT * FROM files_uploaded WHERE file_id = 'delete'";

 

As my previous code deleted all files in a directory, i have now changed the code to below, but this only deletes one file and not two or more even tho they have the same file_id in the database.

 

$address = '/home/www/mydir/files-uploaded/';
$file = $file_name;
if (is_file($address.$file)) {
unlink($address.$file);
}

 

In the code above the $file_name value is not being shown to you but is stored in the database and displays correctly.

 

How do i get this to delete one or more files depending on the file_id in the database?

If you have a query that is selecting the files you want to delete, then just iterate over the results of the query and delete those files.

 

//Query the file name for those to be deleted
$query = "SELECT file_name FROM files_uploaded WHERE file_id = 'delete'";
$result = mysql_query($query);
//Set path to the files if not included in the DB results
$path = '/home/www/mydir/files-uploaded/';
//Loop through the results and delete teh files
while($row = mysql_fetch_assoc($result))
{
    $file = $address . $row['file_name'];
    if (is_file($file)) {unlink($file); }
}

 

Just replace "file_name" in the two places above with the appropriate field name in your table.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.