Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get remote file mime-type

Tags:

mime-types

php

Hey what is the fastest way to check remote file mime-type... Im thinking about reading some from the first bytes, and maybe more... I spend some hours to think how to make the things right, but nothing on my mind... I must check IF the remote file is mp3, but it must be fastcheck...

like image 911
Марин-Мемо Митрев Avatar asked Sep 29 '12 22:09

Марин-Мемо Митрев


3 Answers

PHP curl_getinfo()

<?php
    # the request
    $ch = curl_init('http://www.google.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);

    # get the content type
    echo curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    # output
    // text/html; charset=ISO-8859-1
?>

output

HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Fri, 09 Apr 2010 20:35:12 GMT
Expires: Sun, 09 May 2010 20:35:12 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219

To actually confirm if the file contains actual MP3 data or any other media format, I use getID3().

like image 148
Favourite Onwuemene Avatar answered Nov 20 '22 20:11

Favourite Onwuemene


When checking only the Content-Type of the remote server you're trusting it:

  • The remote server could be malicious and serve a wrong Content-Type on purpose
  • Content-Type is generated using the file extension, so a malicious user could store a wrong file type with an authorized extension to bypass your security

A safer approach is download the file in a temporary folder and then use mime_content_type to check the MIME-type locally using magic.mime.

This technique only use the magic number, only reading the first bytes (header) of the file, that can be bypassed.

The most secure approach is to use a library that verify that the given file is valid for the required type it should be.

like image 37
noraj Avatar answered Nov 20 '22 20:11

noraj


Make a HEAD request. See what Content-Type the server claims it is.

This stackoverflow question discusses accessing HTTP headers via PHP.

like image 43
Quentin Avatar answered Nov 20 '22 19:11

Quentin