I have to upload a pdf type of file only. There are different ways by which we can check the extension of the file like $_FILES['files']['type'] or pathinfo() function. But what if a person changes the extension of the file before uploading. Example. If a person changes a png file from image.png to image.pdf. Then how can I check that the uploaded file is not a pdf?
Asked
Active
Viewed 983 times
-1
-
http://php.net/manual/en/function.finfo-file.php MIME Type – cmorrissey Feb 19 '15 at 17:07
-
Here : http://stackoverflow.com/questions/11514166/check-file-size-before-upload – Bouffe Feb 19 '15 at 17:07
-
All valid PDF files start with the 4 bytes `%PDF` – Phylogenesis Feb 19 '15 at 17:08
-
Checking extension is easy. But checking that the file is an actual PDF. Much harder. Maybe you can get a PDF reader and verify that it can open and read the pdf. – jarchuleta Feb 19 '15 at 17:08
-
@Bouffe still didn't find how to ensure that the file extension is not changed! – Abhinav Kaushal Keshari Feb 19 '15 at 18:03
1 Answers
0
try this
echo mime_content_type('form.pdf');
check more info in http://php.net/manual/es/function.mime-content-type.php
EDIT:
I rename a .zip file to .pdf file
if(isset($_FILES['archivo']) && is_uploaded_file($_FILES['archivo']['tmp_name']))
{
$archivo = $_FILES['archivo']['tmp_name'];
$archivo_name = $_FILES['archivo']['name'];
echo mime_content_type($archivo);
move_uploaded_file($archivo, "upload/" . $archivo_name);
}
the script above print application/zip
Then you can do something like this:
if (mime_content_type($_FILES['archivo']['tmp_name']) == 'application/pdf') {
//ok is a pdf
}

Adrian Cid Almaguer
- 7,815
- 13
- 41
- 63
-
Any better method? As this shows text/plain for some of the pdfs! – Abhinav Kaushal Keshari Feb 19 '15 at 17:55
-
as the manual say you can use $_FILES['userfile']['type'] but this mime type is however not checked on the PHP side and therefore don't take its value for granted. Read more at http://php.net/manual/en/features.file-upload.post-method.php – Adrian Cid Almaguer Feb 19 '15 at 18:02