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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2610713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:06:41  来源:igfitidea点击:

Get mime type of external file using cURL and php

phpcurlmime-types

提问by Ryan

I've used mime_content_type()and File info but i never successed. 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. ( i think the mime type of MP3 is audio/mpeg)

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

Briefly, i know that but i don't know how to apply it :)

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

Thanks

谢谢

回答by ma?ek

PHP curl_getinfo()

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
?>

curl

卷曲

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

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

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

回答by Mark

You can use a HEAD request via curl. Like:

您可以通过 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]);
    }
}

Which returns: image/png

返回:图像/png

回答by Danila Vershinin

If you are ok with a more elegant Zend Framework version, here is a classwhich 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);