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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.