How to Auto Delete Uploaded Files When Record is Deleted or Attachment was Deleted?

I noticed that when uploading files, upon change of uploaded files or deletion of the actual record, the uploaded file is retained in the upload folder of my site.

Is there a way to automatically delete them upon doing those actions?

I tried using PHP’s unlink but no luck…

Thanks in advance!

Hello @larasmith and welcome to our new forums :star2:

Currently the implementation that we have doesn’t support the delete file with actual delete of the file as it was a security issue. The good news is that currently I am refactoring some parts of the upload functionality for the next release (2.9.0) so I can include some callbacks for the deletion of the file.

As there are still the same security issues it is very possible that I will not have a configuration of “real_file_delete_on_delete” (true or false) as this can still be a security issue for a various of reasons that I can send you through PM if you are interested :slight_smile:

The release will probably come sooner than later but till then, you can use the callbackBeforeUpdate and use unlink. If you’ve already done that maybe you can send us some code to check the callback that you used? Also can you please us know which version of Grocery CRUD Enterprise are you using?


1 Like

Hi @johnny! It so nice to be back in using GroceryCRUD :sunglasses:.

This version that I am currently working on is still on version 2.7.9.

I created a callback that was able to delete the uploaded file:

  function deleteAccessFile($file)
      $filePath = $_SERVER['DOCUMENT_ROOT'].'/'.FOLDERNAME."/assets/uploads/$file"; 

      if (file_exists($filePath)) {
        // Use unlink() function to delete a file 
        if (!unlink($filePath)) { 
          $message = ("$filePath cannot be deleted due to an error."); 
        } else { 
          $message = ("$filePath has been deleted."); 

      } else {
          $message = "The file $filePath does not exist.";

      return $message;

Currently, I use this before the deletion of the record:

      $crud->callbackBeforeDelete(function ($stateParameters) {
          $file = $this->m_FileProcessing->getFileName($stateParameters->primaryKeyValue);

          return $stateParameters;  

I hope it helps someone too :blush:

I am glad that you could find a work-around for this @larasmith ,

As always thank you to always help the community :slight_smile:


1 Like