1

For an upload file type checking , I have implemented:

$_FILES["file"]["type"][$i] == 'application/pdf'

however, this checking will not work on the case I changed the extension name.

So , after some research, I have tried

$finfo = new finfo();
$fileMimeType = $finfo->file($_FILES["file"]["name"][$i] );

OR:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$fileMimeType = finfo_file($finfo,$_FILES["file"]["name"][$i])

however, $fileMimeType echo nothing.

How to fix the problem? thanks

user782104
  • 13,233
  • 55
  • 172
  • 312
  • 2
    you can use `file` shell command, or `fread` the first few bytes of the file then you can know the type. – DevZer0 Jul 19 '13 at 09:22
  • would you mind provide an example for a upload file case? thanks – user782104 Jul 19 '13 at 09:23
  • Why would you change the extension? –  Jul 19 '13 at 09:23
  • You may be interested in this post [Why am I getting mime-type of .csv file as “application/octet-stream”?](http://stackoverflow.com/questions/12061030/why-am-i-getting-mime-type-of-csv-file-as-application-octet-stream) – bansi Jul 19 '13 at 09:25
  • @user782104 i have posted an answer for you. – DevZer0 Jul 19 '13 at 09:30

3 Answers3

6

Read the first 4 bytes of the file and check that they match %PDF.

$filename = "pdffile";
$handle = fopen($filename, "r");
$header = fread($handle, 4);
fclose($handle);

Check $header against %PDF

Hein Andre Grønnestad
  • 6,885
  • 2
  • 31
  • 43
  • When you say check do you mean in_array($header, "%PDF"); ? Not sure how to do this with the % –  Aug 09 '16 at 20:50
1

if you read the file using fread you need to have a dictionary of all the file header type definitions. If you want to use the file shell command

$out = exec("file 'R-intro.pdf' | cut -d: -f2 | cut -d, -f1");
if (trim($out) == "PDF document") {
   echo "1";
}

To further expand on how to replace the constant file name with a uploaded file refer below.

$out = exec("file '" . $_FILES['file']['tmp_name'] . "' | cut -d: -f2 | cut -d, -f1");
DevZer0
  • 13,433
  • 7
  • 27
  • 51
  • Thanks for answering . As i am checking upload file , which should be a temp file ( $_FILES["file"]["name"][$i] ) , how can I check it using shell script ? – user782104 Jul 19 '13 at 09:31
  • this is not a shell script, this is php script using a shell command, you need to replace the `R-intro.pdf` with the tmp file name – DevZer0 Jul 19 '13 at 09:32
1

I guess the problem is using:

$_FILES["my_file"]["name"]

as it only contains the name of the uploaded file. If you want to check the file before moving it using move_uploaded_file you can refer to the temp file using:

$_FILES["my_file"]["tmp_name"]
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126