【问题标题】:PHP + CURL How to get file namePHP + CURL 如何获取文件名
【发布时间】:2010-12-31 07:13:43
【问题描述】:

我正在尝试使用此功能在 PHP 中从 facebook 下载用户个人资料图片

public static function downloadFile($url, $options = array())
{
    if (!is_array($options))
        $options = array();
    $options = array_merge(array(
                                 'connectionTimeout' => 5, // seconds
                                 'timeout' => 10, // seconds
                                 'sslVerifyPeer' => false,
                                 'followLocation' => true, // if true, limit recursive redirection by
                                 'maxRedirs' => 2, // setting value for "maxRedirs"
                                ), $options);

    // create a temporary file (we are assuming that we can write to the system's temporary directory)
    $tempFileName = tempnam(sys_get_temp_dir(), '');
    $fh = fopen($tempFileName, 'w');

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_FILE, $fh);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $options['connectionTimeout']);
    curl_setopt($curl, CURLOPT_TIMEOUT, $options['timeout']);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $options['sslVerifyPeer']);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $options['followLocation']);
    curl_setopt($curl, CURLOPT_MAXREDIRS, $options['maxRedirs']);
    curl_exec($curl);

    curl_close($curl);
    fclose($fh);

    return $tempFileName;
}

问题在于它将文件保存在 /tmp 目录中,名称随机且没有扩展名。如何获取文件的原始名称(我对原始扩展名更感兴趣)

这里重要的事情是:

  • 网址实际上重定向到图片,所以我无法从原始网址获取它
  • 最终的 url 在 headers 中没有文件名

【问题讨论】:

    标签: php facebook curl download


    【解决方案1】:

    如果 URL 重定向到图像,您仍然应该能够从标题中获取文件名。使用带有 Chrome 等开发工具的浏览器,您可以查看从原始请求到结果文件的来回标头,并且文件名必须在某处。话虽如此,我的印象是 Facebook 出于隐私原因将所有图像重写为自己的文件名。

    您可以根据响应的内容类型重新创建扩展。

    运行 curl_exec() 后,尝试:

    $content_type = curl_getinfo($curl,CURLINFO_CONTENT_TYPE);
    

    例如,这将为 JPEG 返回类似“image/jpg”的内容。然后,您可以重命名您的临时文件以具有正确的扩展名。

    如果你可以使用 PHP 5.3,一个可能更简洁的方法就是在文件下载后调用 finfo_file(),它应该读取 MIME 类型,允许你选择适当的扩展而不依赖头数据。 finfo_file() 也可用于 fileinfo PECL 扩展。

    【讨论】:

      【解决方案2】:

      如果您只是在寻找图像类型 (jpg/png/gif) 并且安装了 GD 扩展程序,您可以使用getimagesize,它会返回图像类型以及其他详细信息。这比查看文件扩展名更准确。

      一旦您使用了getimagesizeimage_type_to_mime_type 也可能会有所帮助。

      【讨论】:

        猜你喜欢
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-09
        • 2012-06-15
        • 2015-03-19
        相关资源
        最近更新 更多