且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-19 18:05:40

服务器不支持Range标题。您可以做的***的是,一旦收到更多的数据,你想要取消连接。示例:

The server does not honor the Range header. The best you can do is to cancel the connection as soon as you receive more data than you want. Example:

<?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包装(这也将使用curl,如果它被编译 - with-curlwrappers )。基本上,你会在循环中调用 fread ,然后在流上有 fclose ,当你得到的数据超过你想要的数量。您也可以使用传输流(使用 fsockopen 打开流,而不是 fopen 并手动发送标头)if allow_url_fopen 已停用。

Perhaps more cleanly, you could use the http wrapper (this would also use curl if it was compiled with --with-curlwrappers). Basically you would call fread in a loop and then fclose on the stream when you got more data than you wanted. You could also use a transport stream (open the stream with fsockopen, instead of fopen and send the headers manually) if allow_url_fopen is disabled.