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.
please post the code you are using along with the generated error.
– RFL
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
– Daniel Omine