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: https://coursesweb.net/
// $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);
readfile($file);
exit;
2. Set header with the mime-type of a content from an URL address.
// here add the getMimeType() function
$url = 'https://coursesweb.net/imgs/coursesweb.png';
$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;
exit;
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which HTML5 tag can be used to embed an external application (SWF, PDF) in web page?
<mark> <embed> <canvas><embed src="flash_game.swf" width="450" height="350" />
Which CSS pseudo-element adds a special style to the first line of a text?
:first-letter :before :first-line#id:first-line {
font-weight: bold;
color: blue;
}
Click on the window object property which gets or sets the URL of current page.
window.location window.self window.statusvar url = window.location;
alert(url);
Indicate the PHP function used to get the contents of a file or page and store it into a string.
fopen() file_put_contents() file_get_contents()$homepage = file_get_contents("http://coursesweb.net/");
echo $homepage;