Determining the file type of a local file (content type) using PHP

I am trying to determine the mime file type. I tried several methods, but did not come up with anything that gives a consistent result. I tried $mime = mime_content_type($file)and $mime = exec('file -bi ' . $file). I serve images, CSS and JavaScript.

Example mime_content_type()output:

  • jquery.min.js - text / plain
  • editor.js - text / plain
  • admin.css - text / plain
  • controls.css - application / x-troff
  • logo.png - text / plain

Example exec(...)output:

  • jquery.min.js - text / plain; Charset = US-ASCII
  • editor.js - text / x-C ++; Charset = US-ASCII
  • admin.css - text / xc; Charset = US-ASCII
  • controls.css - text / xc; Charset = US-ASCII
  • logo.png - image / png

As you can see here, the results are everywhere.

My PHP version is 5.2.6


SOLUTION (thanks to Jacob)

$mimetypes = array(
    'gif' => 'image/gif',
    'png' => 'image/png',
    'jpg' => 'image/jpg',
    'css' => 'text/css',
    'js' => 'text/javascript',
);
$path_parts = pathinfo($file);
if (array_key_exists($path_parts['extension'], $mimetypes)) {
    $mime = $mimetypes[$path_parts['extension']];
} else {
    $mime = 'application/octet-stream';
}
+3
1

Fileinfo , a >= 5.30

  • mime_content_type PHP 5.30

, , < 5.30, , , , , , /.

:

<?php
$filename = 'FILENAME HERE';
$mimetypes = array('png' => 'image/png', 'jpg' => 'image/jpg', 'css' => 'text/css',
    'js' => 'application/x-javascript'
    // any other extensions that you may be serving      
);

$ext = strtolower(substr($filename, strrpos($filename, '.') + 1, strlen($filename)));
if(array_key_exists($ext, $mimetypes)) {
    $mime = $mimetypes[$ext];
} else {
    echo 'mime type not found';
}

?>
+4

Source: https://habr.com/ru/post/1737167/


All Articles