To compare the files with your database, we can put the name of the files and the name of the images of your BD in two arrays. So we’ll only call the bank once.
The code below records the name of the files with the full path in a $files array, save the name of the images (check if they have the path) in the $images array and check if each file exists in the BD, printing on the screen those that do not exist.
If you are actually deleting the files, make a backup of the directory, check if php has permissions to delete these files and uncomment the last lines of code.
<?php
// Encontra nomes dos arquivos de determinada pasta e salva no array $files
$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);
// Busca nome das imagens no seu Banco de Dados (a conexão já deve estar estabelecida)
$loadImg = mysql_query('SELECT * FROM imagem_imovel');
while($checkImg = mysql_fetch_assoc($loadImg)){
$images[] = $checkImg['imaNome'];
// ATENÇÃO, SE AS IMAGENS NO BD NÃO ESTIVEREM COM O MESMO PATH DOS ARQUIVOS, COMENTE A LINHA ACIMA E DESCOMENTE A SEGUINTE:
//$images[] = '/path/to/directory/' . $checkImg['imaNome'];
};
//verifica se o nome de arquivo existe no Banco de Dados. Se não existir, imprime na tela
foreach($files as $file){
if(!in_array($file, $images)){
// imprime no console (\n para pular linha). Se for para imprimir no html use <br>
echo $file . "\n";
// Se quiser realmente deletar os arquivos, descomente o código abaixo:
//if (file_exists($file))
// unlink($file);
}
}
?>
Is this something that will run daily? If not then it’s okay to delay, if so, do you really need to do it as quickly as possible? If not, you already know, if so, then probably shouldn’t
SELECT * FROM ...
– Costamilam
It will be executed only once, but error 503 always happens.
– Vinicius Yuri