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 .