0

I am storing some files in public folder, programmatically I want to delete those files through the provided path. I tried using below code, but not worked.

function delete_public_files($arg1, $arg2){ 
  $uri = 'public://'; 
  $path= file_create_url($uri);
  $fullpath = $path.$arg1.'/'.$arg2;

  //file_unmanaged_delete($fullpath);

  $fid = db_query("SELECT fid FROM {file_managed} WHERE uri = :path", array(':path' => $fullpath))->fetchField();
  if ($fid) {
    $file = file_load($fid);
    file_delete($file);
  }
  else {
    file_unmanaged_delete($fullpath);
  }
} 

These files are not recorded in the file_managed table and file_usage table also. So how can I delete these files. If I pass the path to file_delete($fullpath); It will says error that first argument should be object. So how can I achieve all these things. Thanks for any appreciation.

2

file_delete deletes a file where it is located and its database record also.

First check file_load whether it is rendering an object file.

// load the file
$file = file_load('YOUR_FILE_ID');

// delete file from disk and from database
file_delete($file);

The file_delete() also takes a second argument $force that if set to TRUE will remove the file even if it's reported as in use by the file_usage table.

use drupal_unlink($fullpath) if files are not recorded in the file_managed table and file_usage table.

See this

  • Thank you for this information.I have mentioned that Files storage record is not at all present in any table of the database.So if loop will fails, but else loop should work rite. – Suraj Aug 9 '16 at 9:39
  • @AAjayKumarReddy You should make it as answer. – Jimmy Ko Aug 9 '16 at 9:43
  • 1
    @Jimmy , edited previous answer and included in that. – Ajay Reddy Aug 9 '16 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.