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

1

I have a problem that I'm breaking my head to solve.

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

The intent is to exclude files that are not on this allowed list.
I've tried (and I'm still trying) to do this using php's "DirectoryIterator" and I'm also testing "scandir", but everything is unsuccessful so far.

I wanted to know if this is possible to do. I believe the difficulty in this is in comparing arrays (allowed and not allowed files) and converting the values of each position of those arrays into variables that can be treated.

As a beginner on the subject I wanted your help to try to solve this problem.

Thank you in advance!

    
asked by anonymous 26.07.2017 / 17:37

1 answer

0

Hello! To truly validate the file type, you can not just trust the name extension (* .pdf, * .xls, etc). You need to read the first few bytes of the file and compare them to expected patterns. For some more 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 load the file via file_get_contents() ). In it, only the PDF file types, JPG or JPEG image (no matter the extension) and PNG image are allowed.

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 had to be compared manually with '%PDF-1' , already for the images PHP had the constants IMAGETYPE_JPEG and IMAGETYPE_PNG .

As a reference of the formats, see the link page, such as link .

    
27.07.2017 / 14:25