Forums

Delete uploaded file based on a db record details.

weprde 26 Aug, 2014
Hello,

I use Chronoforms v4 and Joomla 3.3.1.

I created a form to upload a file (field name ‘attachment’ at the cf ‘upload file’ element) along with some other details such as name, email etc (text boxes). The details with the filename are stored in a db table.

Also, I have created a form to list (LIST FORM) all records and another one to delete (DELETE FORM) one record at a time from the db table. By the ways the Chronoforms made that easy. It’s great!

The problem I have is that although the specific record (based on the cf_uid that is pass via url from the LIST FORM to the DELETE FORM) is deleted using some custom code on the ‘On Submit’ action, I cannot delete the file that is stored in a Joomla folder.

Specifically, I have 3 hidden fields, ‘cf_id’, ‘cf_uid’ and ‘attachment’. The ‘attachment’ keeps the name of the file that was uploaded before and {attachment} has the correct value.

Also, in the ‘On Submit’ I have one custom code element to delete the record and another one to delete the file. The file is stored in JPATH_SITE.'/images/upfiles/*' folder.

What I am trying to do is to read the file name stored in the ‘attachment’ db column, and then for each file that exists in the Joomla folder to read its name and to check if its name is the same as the value in the ‘attachment’ db column.

The custom code that I tried is shown below:

1st version:
<?php
$files = glob(JPATH_SITE.'/images/ upfiles /*');
foreach ($files as $v)
{
  if (isfile($v) && getFilename($v) == $('attachment').value)
  {
    unlink($v);
  }
}
?>

2nd version:
<?php
$files = glob(JPATH_SITE.'/images/ upfiles /*');
foreach ($files as $v)
{
if (isfile($v) && $v['basename']; == $('attachment').value)
  {
    unlink($v);
  }
}
?>


Probably either I am not reading filename and attachment name correctly or both.

Any ideas to solve this?

Thank you.
GreyHead 26 Aug, 2014
Hi weprde,

You have some extra spaces in the paths you posted that will break the code.

But why search all the files? You know the file name and path so you can check on the specific file and delete that.

Bob
weprde 26 Aug, 2014
Bob, thank you for your answer.

Just for the record, the following code works:
<?php
$files = glob(JPATH_SITE.'/images/upfiles/*');

$db =& JFactory::getDBO();
$query="SELECT attachment FROM `#__chronoforms_data_TABLENAME`
    WHERE `cf_uid` = '{$form->data['token']}' ";
$db->setQuery($query);
$attachment= $db->loadResult();

$attachment = "....static part of the path....." . $attachment;

foreach ($files as $v)
{

if ($v == $attachment)
  {
    unlink($v);
  }
}

?>

Probably, Bob's suggestion to directly delete the file (since I have both path and filename) works, too.

Thank you.
This topic is locked and no more replies can be posted.