Reputation: 63
I have a directory with images and I need to check a specific column of a table in my joomla database to see which files exist in the directory but not in the database and delete them.
What I've tried so far has not worked at all
my code is this
$dir = 'directory/of/files';
$files1 = scandir($dir);
$db =& JFactory::getDBO();
$query = "SELECT image FROM #__tablename WHERE something LIKE 'something else'";
$db->setQuery($query);
$result = $db->loadResultArray();
foreach ( $files1 as $file ) {
if (stripos($result, $file) === false) {echo 'file '.$file.' does not exist in database '; unlink($dir.$file);}
else {echo 'file '.$file.' exists in db ';}
}
Any ideas?
Thank you in advance
Upvotes: 0
Views: 171
Reputation: 63
This is the code that I finally managed to write and do what I need
$preImagePath = 'some/path/';
$fullImagePath = $params->get('extra1');//more of the path
$value = $params->get('extra3');
$initfile = scandir($preImagePath.$fullImagePath);
$files1 = array_diff($initfile, array('.', '..'));
$db =& JFactory::getDBO();
$query = "SELECT image FROM #__table WHERE column LIKE '".$value."'";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result ) {
$imagearray .= $result->image.' ';
}
foreach ( $files1 as $file ) {
if (strpos($imagearray, $fullImagePath.$file) === false) { unlink($preImagePath.$fullImagePath.$file); }
}
Upvotes: 0
Reputation: 988
You problem is that in if(stripos($result, $file))
, $result is an array, not a string. Turn on error reporting in the Joomla Configuration to see this. You should be seeing a message like:
Warning: stripos() expects parameter 1 to be string
However, I recommend the following change as it is a bit cleaner:
$dir = 'directory/of/files';
$files1 = scandir($dir);
$db = JFactory::getDBO();
$query = "SELECT image FROM #__tablename WHERE something LIKE 'something else'";
$db->setQuery($query);
$result = $db->loadResultArray();
$diff = array_diff($files1, $result);
// print_r($diff);die;
foreach ( $diff as $file ) {
unlink($dir.$file);
}
Uncomment the print_r
first to check it is what you want.
Upvotes: 1