【问题标题】:Check if URL is a zip检查 URL 是否为 zip
【发布时间】:2016-10-27 20:49:42
【问题描述】:

我如何确定一个 URL 是否为 ZIP,但不先下载整个 URL,因为它可能太大了?我能以某种方式只获取几个字节并检查 ZIP 标头吗?

【问题讨论】:

  • 检查 zip 标头是最安全的。 quick/dirty 将执行 HEAD 请求并查看内容类型是否为 application/zip
  • 您可以使用CURLOPT_RANGE 指定要下载的字节范围。因此,请指定类似0-64 的内容来获取文件的前 64 个字节。但见stackoverflow.com/questions/6048158/…

标签: php http curl zip


【解决方案1】:

我从 this answer 修改了我的代码,改为从响应中读取 4 个字节(使用范围,或在读取 4 个字节后中止),然后查看 4 个字节是否与 zip 魔术头匹配。

试一试,让我知道结果。如果 curl 请求因某种原因失败,您可能需要添加一些错误检查以查看是否无法确定文件的类型。

<?php

/**
 * Try to determine if a remote file is a zip by making an HTTP request for
 * a byte range or aborting the transfer after reading 4 bytes.
 *
 * @return bool true if the remote file is a zip, false otherwise
 */
function isRemoteFileZip($url)
{
    $ch = curl_init($url);

    $headers = array(
        'Range: bytes=0-4',
        'Connection: close',
    );

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2450.0 Iron/46.0.2450.0');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0); // set to 1 to debug
    curl_setopt($ch, CURLOPT_STDERR, fopen('php://output', 'r'));

    $header = '';

    // write function that receives data from the response
    // aborts the transfer after reading 4 bytes of data
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) use(&$header) {
        $header .= $data;

        if (strlen($header) < 4) return strlen($data);

        return 0; // abort transfer
    });

    $result = curl_exec($ch);
    $info   = curl_getinfo($ch);

    // check for the zip magic header, return true if match, false otherwise
    return preg_match('/^PK(?:\x03\x04|\x05\x06|0x07\x08)/', $header);
}

var_dump(isRemoteFileZip('https://example.com/file.zip'));
var_dump(isRemoteFileZip('https://example.com/logo.png'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多