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

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 107

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

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?

Admin Posts: 805
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

Similar Topics