[英]Get mime type of external file using cURL and php
I've used mime_content_type()
and File info but i never successed.我使用了
mime_content_type()
和 File info 但我从未成功过。 i want to use now cURL with PHP and get the headers of the file which is hosted on another domain then extract & determine if the type is MP3 or not.我现在想在 PHP 中使用 cURL 并获取托管在另一个域上的文件的标题,然后提取并确定类型是否为 MP3。 ( i think the mime type of MP3 is
audio/mpeg
) (我认为 MP3 的 mime 类型是
audio/mpeg
)
Briefly, i know that but i don't know how to apply it :)简而言之,我知道,但我不知道如何应用它:)
Thanks谢谢
<?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 -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
You can use a HEAD request via curl.您可以通过 curl 使用 HEAD 请求。 Like:
喜欢:
$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]);
}
}
Which returns: image/png返回:图像/png
If you are ok with a more elegant Zend Framework version, here is a class which makes use of Zend_Http_Client component.如果您对更优雅的 Zend Framework 版本没有意见, 这里有一个使用 Zend_Http_Client 组件的类。
Use it like so:像这样使用它:
$sniffer = new Smartycode_Http_Mime();
$contentType = $sniffer->getMime($url);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.