php - 无法限制 PHP 的 cURL 函数的下载大小

标签 php curl http-headers

我正在使用 PHP 的 cURL 函数从 steampowered.com 读取配置文件。检索到的数据是 XML,只需要前大约 1000 个字节。

我使用的方法是添加一个 Range header ,这是我在 Stack Overflow 答案 ( curl: How to limit size of GET? ) 上读到的。我尝试的另一种方法是使用 curlopt_range,但这也不起作用。

<?
$curl_url = 'http://steamcommunity.com/id/edgen?xml=1';
$curl_handle = curl_init($curl_url);

curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($curl_handle, CURLOPT_HTTPHEADER, array("Range: bytes=0-1000"));

$data_string = curl_exec($curl_handle);

echo $data_string;

curl_close($curl_handle);
?>

执行此代码时,它会返回全部内容。

我使用的是 PHP 版本 5.2.14。

最佳答案

服务器不接受 Range header 。你能做的最好的事情就是在你收到比你想要的更多的数据时立即取消连接。示例:

<?php
$curl_url = 'http://steamcommunity.com/id/edgen?xml=1';
$curl_handle = curl_init($curl_url);

$data_string = "";
function write_function($handle, $data) {
    global $data_string;
    $data_string .= $data;
    if (strlen($data_string) > 1000) {
        return 0;
    }
    else
        return strlen($data);
}

curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($curl_handle, CURLOPT_WRITEFUNCTION, 'write_function');

curl_exec($curl_handle);

echo $data_string;

也许更干净,你可以使用 http 包装器(如果它是用 --with-curlwrappers 编译的,这也会使用 curl)。基本上,您会在循环中调用 fread,然后在您获得的数据多于您想要的数据时在流上调用 fclose。如果禁用了 allow_url_fopen,您还可以使用传输流(使用 fsockopen 而不是 fopen 打开流并手动发送 header )。

关于php - 无法限制 PHP 的 cURL 函数的下载大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431703/

相关文章:

php - 如何使file_get_contents()与HTTPS一起使用?

curl (56) 接收失败

java - Spring Boot @RequestBody 只解析 0/null 值?

javascript - 获得 Websocket 连接的完整响应

php - 如何在 Laravel 中同步同一个属性的多个值?

php - PHP中如何获取客户端真实IP地址?

php - 为什么 Yahoo Social SDK for PHP 的示例代码总是为 session 变量返回 NULL?

http - 通过 HTTP header 的规范 URL 规范

javascript - 使用 axios 在 VueJS 中进行预检请求

php - 用于检查资源是否为用户所有的中间件