3
votes

I am creating an web application that allows users to upload pdf documents. The following is the code to check(Restrict) the document type to pdf.

if (isset($_POST['submitbutton'])) {
  $name = $_FILES['myfile']['name'];
  $type = $_FILES['myfile']['type'];
  $size = $_FILES['myfile']['size'];
  $tmpname = $_FILES['myfile']['tmp_name'];
  $ext = substr($name, strrpos($name,'.'));  //Get the extension of the selected file
  echo $type.' This is the type';
  echo '<br>';
  if (($type == "application/pdf")||($type == "application/octet-streamn")) {
    echo 'ok';
  } else {
    echo "That is not a pdf document";
  }
}

I checked the types by echo(ing) $type to the screen. But the type output is different for firefox. I just need to confirm the following mime types. Am I correct when I say:

Internet explorer : application/pdf

Opera: application/pdf

FireFox : application/octet-streamn

or is there a standard mime type that covers all existing browsers. Please help, I am still getting my feed wet with php and files

2
You can't know what the file really is if you rely on the mime-type. Anyone can send a .php file and fake it's image/gif or similar. That's why we don't trust user input, and file upload is user input.N.B.
Do not trust anything sent from the user. It would be super simple to send a PHP file with the mime type application/pdf.h2ooooooo
The output I get if I use application/pdf only for checking file type says it not a pdf on firefox. is there a work around it ? because I dont think I can exclude file checking for pdf's on firefoxkya

2 Answers

4
votes

Don't trust $_FILES['myfile']['type'] as it is provided by the client. A better solution is to use finfo_open:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $_FILES['myfile']['tmp_name']);
if($type == 'application/pdf'){
    //Is a PDF
}
0
votes

To avoid confusion, and browser issues use JQuery

var filename="";
$('#upload').on( 'change', function() {
filename= $( this ).val();
var exten = filename.split('.').pop();
if(exten!="pdf"){
    alert("Only pdf documents are allowed");
    $(this).val('');
}
});