delete uploaded file from an array of id when they are delted in joomla?
I am trying to delete an array of ids and when it gets deleted I want the uploaded pic associated with it also to get deleted using unlink. I am using joomla and mysql for the admin mvc component in joomla.
My code for controller in remove is has follows:
function remove()
{
$arrayIDs = JRequest::getVar ( 'cid', null, 'default', 'array' );
//Reads cid as an array
$model = & $this->getModel ( 'greetings' );
jimport ( 'joomla.filesystem.file' );
if (is_array ( $arrayIDs ) && count ( $arrayIDs ) > 0) {
foreach ( $arrayIDs as $k => $id ) {
$del = $model->deleteGreetings ( $arrayIDs );
if ($del) {
$getdeleted = $model->getUploadpic ( $id );
$deletefile = JPATH_COMPONENT . DS . "uploads" . DS . $uploadedfile;
unlink ( $deletefile );
}
}
}
if ($arrayIDs === null) { //Make sure the cid parameter was in the request
JError::raiseError ( 500, 'cid parameter missing from the request' );
}
$redirectTo = JRoute::_ ( 'index.php?option=' . JRequest::getVar ( 'option' ) );
$this->setRedirect ( $redirectTo, 'Deleted...' );
}
...and for the model my code is开发者_运维问答:
function deleteGreetings($arrayIDs) {
$query = "DELETE FROM #__greetings WHERE id IN (" . implode ( ',', $arrayIDs ) . ")";
$db = $this->getDBO ();
$db->setQuery ( $query );
if (! $db->query ()) {
$errorMessage = $this->getDBO ()->getErrorMsg ();
JError::raiseError ( 500, 'Error deleting greetings: ' . $errorMessage );
} else {
return TRUE;
}
}
You have a few problems in your code:
$uploadedfile
is never declared but it is used to find the file path. I assume this is the same as$getdeleted
.- You have a foreach loop around the elements in your array which will pick up each element in turn. However you model function
deleteGreetings
takes the entire array. Your should remove this function call from your loop else it will be called each for every element in the array. You only want to call this once. - Only at the end of your controller do you check if your cid param is null ... what is the point? You should check this first before trying to run any of the other code.
I would do something like this:
$arrayIDs = JRequest::getVar ( 'cid', null, 'default', 'array' );
if ($arrayIDs === null) { //Make sure the cid parameter was in the request
JError::raiseError ( 500, 'cid parameter missing from the request' );
}
$model = & $this->getModel ( 'greetings' );
jimport ( 'joomla.filesystem.file' );
if (is_array ( $arrayIDs ) && count ( $arrayIDs ) > 0) {
$del = $model->deleteGreetings ( $arrayIDs );
// check this outside the loop, if it is inside you are checking it for
// each element in the array. Here we check once and then go forward.
if ($del) {
foreach ( $arrayIDs as $k => $id ) {
$uploadedfile = $model->getUploadpic ( $id );
$deletefile = JPATH_COMPONENT . DS . "uploads" . DS . $uploadedfile;
JFile::delete($deletefile);
//unlink ( $deletefile );
}
}
}
精彩评论