【问题标题】:Get mime type of external file using cURL and php使用 cURL 和 php 获取外部文件的 mime 类型
【发布时间】:2010-04-09 20:33:13
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: php curl mime-types


    【解决方案1】:

    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 -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 提供的本地工具。
    【解决方案2】:

    您可以通过 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

    【讨论】:

    • 太好了!它只会获取标题并为大图像节省大量时间和资源。如果您现在正在使用它 - 将拆分功能更改为爆炸(因为它已从 php5.3 弃用)
    【解决方案3】:

    如果您可以使用更优雅的 Zend Framework 版本,here is a class 它使用 Zend_Http_Client 组件。

    像这样使用它:

    $sniffer = new Smartycode_Http_Mime(); 
    $contentType = $sniffer->getMime($url);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-19
      • 2018-12-01
      • 2012-11-03
      • 2013-04-02
      • 2014-06-10
      • 2014-05-19
      • 1970-01-01
      相关资源
      最近更新 更多