PHP 5.3.0 and later have finfo class with methods to get the content type and encoding of a file or string content, by looking for certain magic byte sequences at specific positions within that file /content.
- The getMimeType() function presented in this page uses the finfo class to return the Mime Type of a file, or a String content, in PHP.
This function is useful if you want to output a content with a header() that contains the correct Content-Type.
- Click on the code to select it.
function getMimeType($r, $t='file') {
//Returns the Mime Type of a file or a string content - from:
// $r = the resource: Path to the file; Or the String content
// $t = type of the resource, needed to be specified as "str" if $r is a string-content
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  return ($t =='str') ? $finfo->buffer($r) : $finfo->file($r);
- If you want to get the mime-type of a file, just call the getMimeType() function with the path of that file.
- To get the mime-type of a string-content, call this function with the string-content and "str" as the 2nd argument.

• Examples:
1. Set header with the Content-Type of a file on server.
// here add the getMimeType() function

$file = 'path_to/file.pdf';
$mime_type = getMimeType($file);

// set the header and outputs the file
header('Content-Type: '. $mime_type);
2. Set header with the mime-type of a content from an URL address.
// here add the getMimeType() function

$url = '';
$cnt = file_get_contents($url);  //gets the string content
$mime_type = getMimeType($cnt, 'str');  //get the mime-type of the content in $cnt

// set the header and outputs the content
header('Content-Type: '. $mime_type);
echo $cnt;

Daily Test with Code Example

Which tag create a highlighted bolded text?
<q> <strong> <em>
<p>Address: <strong></strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;
#id {
  font-weight: 800;
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()
function someFunction() { alert(""); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;
$vname = 8;
echo $vname;
Get Mime Type of file or string content in PHP

Last accessed pages

  1. Butterfly Kyodai (6814)
  2. Zuma Deluxe (10133)
  3. Zodiac Signs JavaScript code (2798)
  4. Integer and Float value in Select with PDO from string to numeric (2799)
  5. Get and change IFrame content through a JavaScript script created in another IFrame (6082)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (47842)
  2. Read Excel file data in PHP - PhpExcelReader (35965)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (35572)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (32081)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (29348)