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...
Asked
Active
Viewed 9,255 times
11
-
Define "remote file"? How is it being accessed? HTTP? SMB? NFS? FTP? IMAP? – Quentin Sep 29 '12 at 22:02
-
Maybe this could help you: [get_headers()](http://php.net/manual/en/function.get-headers.php) – rsz Sep 29 '12 at 22:03
-
What If I only the know the extension of file instead of actual filename then header wont work in that case. Right? What would be solution then through HTTP? – hfarazm Aug 01 '16 at 07:22
3 Answers
16
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().

Favourite Onwuemene
- 4,247
- 8
- 28
- 46
-
Hmm interesting thing, I made file john.mp3 with content and scripts says its a "audio/mpeg", can this be fixed? – Марин-Мемо Митрев Sep 29 '12 at 22:23
-
Unfortunately php Mime-type is generated using just the file extension and not the actual file contents. You would have to make use of some third party app to actually verify that the file actually contains valid mp3 data. – Favourite Onwuemene Sep 29 '12 at 22:29
-
3If you don't want to load the entire file, just read the information about it, you can use these options instead: curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, TRUE); curl_setopt($ch, CURLOPT_NOBODY, TRUE); – viplezer Feb 02 '16 at 09:48
6
Make a HEAD request. See what Content-Type the server claims it is.
This stackoverflow question discusses accessing HTTP headers via PHP.
2
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.

noraj
- 3,964
- 1
- 30
- 38