将标头/内容类型从 cURL 请求传递到当前输出/标头


Pass header/content-type from cURL-request to current output/header

我不知道如何写一个更好的标题。随意编辑。 不知何故,我没有找到任何关于此的内容:

我有一个来自PHP的cURL请求,它返回了一个快速文件。如果我想在浏览器窗口中输出流,这工作正常。但我想发送它,因为它是一个真实的文件。如何传递标头并将其设置为脚本的输出,而无需将所有内容存储在变量中。

脚本如下所示:

if (preg_match('/^['w'd-]{36}$/',$key)) {
    // create url
    $url        = $remote . $key;
    // init cURL request
    $ch         = curl_init($url);
    // set options
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 256);
    if (null !== $username) {
        curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
    }
    // execute request
    curl_exec($ch);
    // close
    curl_close($ch);
}

我可以看到这样的标题和内容,因此请求本身工作正常:

HTTP/1.1 200 OK X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2 Java/Oracle Corporation/1.7) 服务器: GlassFish Server Open Source Edition 3.1.2 内容类型: video/quicktime 传输编码: 分块

从 curl 查询中获取内容类型:

$info = curl_getinfo($ch);
$contentType = $info['content_type'];

并将其发送给客户端:

header("Content-Type: $contentType");

试试这个:

header ('Content-Type: video/quicktime');

在输出内容之前

因此,在前面的答案的帮助下,我让它工作了。在我看来,它仍然有一个要求,但也许有人有更好的方法。

在以下情况下发生的问题:

1.) 像这样使用 cURL 时:

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);

标头未返回内容类型,而仅返回 *'*

2.)使用curl_setopt($ch, CURLOPT_NOBODY, false);获得了正确的内容类型,但也获得了整个内容本身。所以我可以将所有内容存储在变量中,读取标头,发送内容。不知何故不是一个真正的选择。

因此,在获取内容之前,我必须使用get_headers($url, 1);请求一次标头。

3.)最后,HTML5视频标签和jwPlayer都不想播放"index.php的问题。因此,使用 mod_rewrite 并将"name.mov"设置为"index.php"它起作用了:

RewriteRule ^(.*).mov index.php?_route=$1 [QSA]

结果如下:

if (preg_match('/^['w'd-]{36}$/',$key)) {
    // create url
    $url        = $remote . $key;
    // get header
    $header     = get_headers($url, 1);
    if ( 200 == intval(substr($header[0], 9, 3)) ) {
        // create url
        $url        = $remote . $key;
        // init cURL request
        $ch         = curl_init($url);
        // set options
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_BUFFERSIZE, 256);
        if (null !== $username) {
            curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
        }
        // set header
        header('Content-Type: ' . $header['Content-Type']);
        // execute request
        curl_exec($ch);
        // close
        curl_close($ch);
        exit();
    }
}