note 103646 deleted from function.mime-content-type by mazzanet
| From: | mazzanet@php.net | Date: | Tue, 26 Apr 2011 09:49:43 +0000 |
| Subject: | note 103646 deleted from function.mime-content-type by mazzanet | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179148@lists.php.net to get a copy of this message | ||
Note Submitter: te at xeony dot de
----
I've searched a while for some ways to get the MIME Type of a file and nothing makes me happy.
So i wrote a all-in-one variante to get the MIME Type:
<?php
/*
* Usage:
*
* $sMimeType = $oMime::getMimeType('<filepath>');
*
*/
class Mime
{
public static function getMimeType($sFile)
{
if (function_exists('mime_content_type')){
return mime_content_type($sFile);
}
if (function_exists('finfo_file')){
$hFInfo = finfo_open(FILEINFO_MIME);
$mType = finfo_file($hFInfo, $sFile);
finfo_close($hFInfo);
return $mType;
}
if (function_exists('get_headers')) {
$aInfo = get_headers(self::getDomain() . $sFile, 1);
return $aInfo['Content-Type'];
}
if (function_exists('curl_init')) {
$hCURL = curl_init(self::getDomain() . $sFile);
curl_setopt($hCURL, CURLOPT_HEADER, 1);
curl_setopt($hCURL, CURLOPT_NOBODY, 1);
curl_setopt($hCURL, CURLOPT_RETURNTRANSFER, 1);
if (!curl_exec($hCURL)) return false;
$aInfo = curl_getinfo($hCURL);
return $aInfo['content_type'];
}
// Nothing works -.- try to catch it via fsockopen! -.-
$hFP = fsockopen(self::getDomain(false), 80, &$iErrno, &$sErrstr, 30);
if ($hFP) {
$sRequest = "GET " . self::getDomain(true) . $sFile . " HTTP/1.0\r\n";
$sRequest .= "Accept: */*\r\n";
$sRequest .= "Cache-Control: no-cache\r\n";
$sRequest .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.2)
Gecko/2008090514 Firefox/3.0.2\r\n";
$sRequest .= "Host: " . self::getDomain(false) . "\r\n";
$sRequest .= "Connection: Close\r\n";
$sRequest .= "\r\n";
fputs($hFP, $sRequest);
$sLine = '';
$sHeader = '';
while(!($sLine == "\r\n") && !feof($hFP)) {
$sLine = fgets($hFP, 4096);
$sHeader .= $sLine;
}
fclose($hFP);
if (preg_match('/Content-Type: (.*)\n\r/i', $sHeader, $aMatch))
return $aMatch[1];
}
}
public static function getDomain($bProtocol = true, $secure = false) {
$protocol = ((isset($_SERVER['HTTPS']) &&
!empty($_SERVER['HTTPS'])) || $secure === true) ? 'https://' : 'http://';
$domain = $_SERVER['SERVER_NAME'];
return ($bProtocol ? $protocol : '') . $domain;
}
}
?>