ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// path to the images
$path_img='./media/images/inside/gallery';
// where images are listed in database
$table_name='gallery';
$field_name='file';
// unnecessary parts of filenames
$odd_tokens = array("_small", ".jpg", ".");
// limit number of image files to check, set to 10 for testing
$limit=10;
echo "begin\r\n";
//connection constants
include './application/config/config.php';
try{
$pdo = new PDO( 'mysql:host='.config::$db_server.';dbname='.config::$db_name, config::$db_user, config::$db_pass );
}
catch (Exception $e){
echo $e->getMessage();
exit();
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$r=$pdo->query('select count(1) cnt from '.$table_name)->fetch();
echo 'count images in database: '.$r['cnt']."\r\n";
// reset some counters
$cnt_files=0;
$cnt_checked=0;
$cnt_not_found=0;
$cnt_found=0;
$path=$path_img;
if ($handle = opendir($path)) {
while ($cnt_files != $limit && false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$cnt_files++;
if($entry > "") {
$cnt_checked++;
$img_name = str_replace ($odd_tokens,'',$path . '/' . $entry);
if(!checkExistsDb($pdo, $img_name, $table_name, $field_name)) {
$cnt_not_found++;
echo 'rm ' . $path . '/' . $entry . "\r\n";
//this will delete files unlink($path.'/'.$entry);
} else {
$cnt_found++;
}
}
}
}
closedir($handle);
}
else echo 'not found: '.$path."\r\n";
unset($pdo);
echo 'files: '.$cnt_files.' checked: '.$cnt_checked.' not_found: '.$cnt_not_found.' found: '.$cnt_found;
function checkExistsDb($pdo, $img_name, $table_name, $field_name) {
try{
$st = $pdo->prepare('SELECT ' . $field_name . ' FROM ' . $table_name . ' WHERE '. $field_name . '=:filename');
$st->execute(array(':filename'=>$img_name));
$result = $st->fetchAll();
}
catch (PDOException $e) {
echo $e->getMessage();
}
return $result?true:false;
}
感谢
https://www.prestashop.com/forums/topic/290936-cleanup-imgp-folder-and-image-folder-questions/