PHP/FTP File Verification

Asked

Viewed 139 times

1

Hello,

I have the following situation:

My company wants to validate all files from a particular folder on FTP with BD (Mysql), to make sure that all files are being used and those that are not deleted.

The Problem:

The database table has + 1 million records.


I managed to get the list of names of the files in FTP and I can get the list of records in BD, but I can’t compare and generate a result.

Code of the List:

foreach($contents as $file){
    echo $file;
};

Code in the Bank:

$loadImg = mysql_query('SELECT * FROM imagem_imovel');
while($checkImg = mysql_fetch_assoc($loadImg)){
    echo $checkImg['imaNome'];
};

How to compare these two to know if the FTP file name has any record in BD without making a query to each name ?

  • 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 ...

  • It will be executed only once, but error 503 always happens.

1 answer

1

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);

        }
    }
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.