Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't php correctly detect a pdf mime type (wkhtmltopdf)?

The problem.

I created a pdf using wkhtmltopdf and php will not recognize it as a pdf. When I lookup the mime type it returns unknown.

How can I either:

  • Fix wkhtmltopdf hopefully with a setting
  • Adjust php's pdf file recognition algorithm to see it as a pdf.

Code

PHP version 5.6
Apache 2.4
Windows 10 Pro
fileinfo 1.0.5
wkhtmltopdf "0.12.4 (with patched qt)"

$file_info = new finfo(FILEINFO_MIME_TYPE);
return $file_info->file($file_path); // returns "/unknown"

To reproduce.

I can't attache a pdf here but simply run the wkhtmltopdf tool per the instructions on the homepage: wkhtmltopdf http://google.com google.pdf then run the above php code on it.

like image 558
danielson317 Avatar asked Mar 27 '26 02:03

danielson317


1 Answers

Here is the environment, I ran it on:

OS: Win 10 Pro

Apache: Apache/2.4.27 (Win32) OpenSSL/1.0.2l PHP/7.1.9

PHP: 7.1.9

FileInfo: 1.0.5

WkHTMLtoPDF: wkhtmltox-0.12.4_msvc2015

I ran the command on CMD in Admin mode:

 C:\Program Files\wkhtmltopdf\bin>wkhtmltopdf http://google.com google.pdf

And Ran the following PHP code(after moving the google.pdf to my dir inside htdocs):

$file_path = "google.pdf";
$file_info = new finfo(FILEINFO_MIME_TYPE);
var_dump($file_info->file($file_path));

And the output was(Successfully):

C:\xampp\htdocs\htmlpdf\test.php:5:string 'application/pdf' (length=15)

If this isn't working for you, I would suggest the following methods:

1) Using mime_content_type, said to be deprecated

$file_path = "google.pdf";
var_dump(mime_content_type($file_path));

2) Using finfo_open, it is the same as new finfo but still, worth a try:

$file_path = "google.pdf";
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $file_path);
finfo_close($finfo);
var_dump($mimetype);

3) OR if you don't mind using external libraries, and fallback dependencies try:

  1. http://getid3.sourceforge.net/
  2. https://stackoverflow.com/a/3664655
like image 74
mega6382 Avatar answered Mar 29 '26 17:03

mega6382