使用cURL和php获取外部文件的MIME类型

24

我曾经使用过 mime_content_type() 和文件信息,但从未成功。现在我想使用 PHP 中的 cURL 获取托管在另一个域上的文件的头,并提取并确定其是否为 MP3 类型。(我认为 MP3 的 MIME 类型是 audio/mpeg

简而言之,我知道这一点,但不知道如何应用它 :)

谢谢

3个回答

54

PHP curl_getinfo()

:获取一个cURL传输的信息。
<?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
?>

curl

curl -I http://www.google.com

输出结果

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

提醒其他人:如果您正在将外部文件下载到服务器上,则对立服务器提供的MIME类型可能会被故意更改。不要相信内容类型。相反,下载文件并使用PHP提供的本地工具。 - DreamWave

22

你可以使用curl发送一个HEAD请求,如下:

$ch = curl_init();
$url = 'http://sstatic.net/so/img/logo.png';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$results = explode("\n", trim(curl_exec($ch)));
foreach($results as $line) {
    if (strtolower(strtok($line, ':')) == 'content-type') {
        $parts = explode(":", $line);
        echo trim($parts[1]);
    }
}

返回结果为:image/png


1
太好了!它只会获取头文件,为大型图像节省了大量时间和资源。如果您现在正在使用它,请将split函数更改为explode(因为它已从php5.3中弃用)。 - sUP
你不能直接从curl中提取Content-Type:头并跳过其余部分吗?例如 curl --write-out '%{content_type}' --silent $URL - gwern

2
如果您希望使用更优雅的Zend Framework版本,这里有一个类,它使用了Zend_Http_Client组件。
使用方法如下:
$sniffer = new Smartycode_Http_Mime(); 
$contentType = $sniffer->getMime($url);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接