How to list files from a directory and then compare them to a list of allowed files using PHP?

Asked

Viewed 77 times

1

I have a problem I’m cracking my head to solve.

How do I list the files in a directory and then compare them to a list of allowed files using PHP?

The intention of this is to delete files that are not in this permitted list.
I tried (and I’m still trying) to do this using php’s "Directoryiterator" and I’m testing also with "scandir", but all unsuccessful so far.

I was wondering if it could be done. I believe the difficulty in this is in comparing arrays (allowed and not allowed files) and converting the values of each position of these arrays to variables that can be treated.

Since I’m a beginner in the subject I wanted your help to try to solve this problem.

Not put here the code I’m testing because there’s nothing concise in it (it wouldn’t be much help).

Thanks in advance!

  • please post the code you are using along with the generated error.

  • 1

    I marked it as too wide because it asks for two different things. One of them finds an answer here, which is like listing files from a directory: https://answall.com/questions/108662 If you already know how to do something simple, you could be more objective in the question and ask only how to compare two arrays or something like that. And you probably already have an answer for that. Search on the site you’ll find everything you need. https://answall.com/search?q=php+comparar+array

1 answer

0


Hello! To truly validate the file type, you can’t just rely on the name extension (*.pdf, *.xls, etc). You need to read the first bytes of the file and compare them to expected patterns. For some common types PHP has some constants. For all others it is necessary to formulate the comparison manually.

In this example, a function evaluates a file that is submitted via post (but you can simply upload the file via file_get_contents()). In it, only PDF, JPG or JPEG image types are allowed (no matter the extension) and PNG image.

public function validar_arquivo() {
    // Valida o arquivo enviado, e quando incorreto retorna false
    if(isset($_FILES['arquivo'])) {
        // Valida o tamanho, 3145728 bytes = 3072 kB = 3 MB
        if($_FILES['arquivo']['size'] > 3145728) {
            echo('O tamanho do arquivo deve ser inferior ou igual a 3,00 MB.');  
            return false;
        }

        // Valida o conteúdo do arquivo
        if($_FILES['arquivo']['tmp_name']) {
            $file_data = file_get_contents($_FILES['arquivo']['tmp_name']);
            if(substr($file_data, 0, 6) == '%PDF-1') {
                echo('application/pdf');
            } else if(exif_imagetype($_FILES['arquivo']['tmp_name']) == IMAGETYPE_JPEG) {
                echo('image/jpeg');
            } else if(exif_imagetype($_FILES['arquivo']['tmp_name']) == IMAGETYPE_PNG) {
                echo('image/png');
            } else {
                echo('O arquivo enviado não está no formato esperado: arquivo PDF, imagem JPG ou imagem PNG.');  
                return false;
            }
        }

    }   
    return true;
} 

The PDF needed to be manually compared with '%PDF-1', already for the images PHP had the constants IMAGETYPE_JPEG and IMAGETYPE_PNG.

As a reference to the formats, refer to the page: http://filext.com/, as for example in http://filext.com/file-extension/JPG.

  • 1

    Hi @C. Bohok! Thanks for the force, your code has made me fill a more refined level of file validation, and it will most certainly be very useful in my projects.

Browser other questions tagged

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