2

For security purposes as to prevent malicious or unwanted filetypes, how would I identify mimetypes from external/remote files (aka. url links like www.someurl.com/video.avi)? I've read that there is a way using cURL but I would like to find a PHP native solution if possible.

user1307016
  • 383
  • 1
  • 8
  • 17

2 Answers2

12

You can use get_headers

Example:

<?php

$headers = get_headers('http://website.com/image.png');
var_dump($headers);

?>

Outputs:

array(8) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Tue, 08 May 2012 07:56:54 GMT"
  [2]=>
  string(14) "Server: Apache"
  [3]=>
  string(44) "Last-Modified: Sun, 06 May 2012 23:09:55 GMT"
  [4]=>
  string(20) "Accept-Ranges: bytes"
  [5]=>
  string(22) "Content-Length: 707723"
  [6]=>
  string(17) "Connection: close"
  [7]=>
  string(23) "Content-Type: image/png"
}
andyderuyter
  • 1,081
  • 2
  • 8
  • 25
  • 1
    Just wondering how accurate would this be? Can't headers be easily spoofed? – user1307016 May 09 '12 at 00:40
  • Related: [PHP: get_headers set temporary stream_context](http://stackoverflow.com/questions/8429342/php-get-headers-set-temporary-stream-context) – hakre Sep 01 '12 at 11:12
  • Like headers, the file-content can be equally easily spoofed as well. So probably you should make yourself comfortable with the fact that remote files are not under your control so you can not secure them at all. You only can retrieve some information about them *or* you copy them over and host the "secured" copy on your own. – hakre Sep 01 '12 at 11:57
  • If I do not know the name of the file but only extension, then how header will detect file? – hfarazm Aug 01 '16 at 00:16
1

Supposing you don't want to download the full file, you can check the remote server mime type:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
return curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

or also with curl, you could download the full file (generally bad for performances) and then use mime_content_type or finfo_file locally

Luca C.
  • 11,714
  • 1
  • 86
  • 77