Page 1 of 1

Set header with the correct Mime-Type of content from an URL address

Posted: 19 Aug 2015, 15:41
by Marius
Hello
I have this script that gets the content from an URL address and outputs it to the browser.

Code: Select all

$url = 'the_url_address';
$content = file_get_contents($url);  //gets the content

// here i need to set the header with the correct Content-Type
header('Content-Type: ...');
echo $cnt;
exit;  
I need to add the mime-type into the header('Content-Type: ...') to can properly output that resource. But the resource type is variable, it can be a PDF file, a DOC, or an image (JPG, PNG, ...).
So, how can I get the correct Mime Type of a content from an Url address?

Set header with the correct Mime-Type of content from an URL address

Posted: 19 Aug 2015, 16:37
by Admin
Hi,
You can use the finfo class and the buffer() method to get the mime-type of a string-content.
Here is an example:

Code: Select all

$url = 'https://coursesweb.net/imgs/coursesweb.png';
$cnt = file_get_contents($url);  //gets the string content
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $finfo->buffer($cnt);

// set the header and outputs the content
header('Content-Type: '. $mime_type);
echo $cnt;
exit; 
- Or, you can use the getMimeType() function from this page: https://coursesweb.net/php-mysql/mime-ty ... tent-php_t