PHP CURLOPT_WRITEFUNCTION 似乎没有被调用

发布于 2024-12-01 00:43:31 字数 580 浏览 1 评论 0原文

我正在尝试使用curl 读取数据流的一小块。

理想情况下,我只想检索流中的第一个图像并将其写入 jpg 文件。

我尝试使用 WRITEFUNCTION 来执行此操作,如果流的长度 > 则返回 -1比如说 20000。

function receiveResponse($ch,$string) {
    $length = strlen($string);
    if($length >= 20000) { return -1; }
    return $length;
}

$ch = curl_init('http://<url>/videostream.cgi');
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
curl_setopt($ch, CURLOPT_WRITEFUNCTION, "receiveResponse");
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);

然而,流只是继续写入文件,最终文件大小变得越来越大。

我该如何修复它?

I'm trying to read just one chunk of a stream of data using curl.

Ideally I would like to just retreive the first image in the stream and write that to a jpg file.

I'm attempting to do this using WRITEFUNCTION and returning -1 if the length of the stream > say 20000.

function receiveResponse($ch,$string) {
    $length = strlen($string);
    if($length >= 20000) { return -1; }
    return $length;
}

$ch = curl_init('http://<url>/videostream.cgi');
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
curl_setopt($ch, CURLOPT_WRITEFUNCTION, "receiveResponse");
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);

However the stream just continues to write to the file which ends up getting larger and larger in file size.

How can I fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷心人i 2024-12-08 00:43:31

让我们看看本手册中的选项说明 http://www.php.net /manual/en/function.curl-setopt.php

CURLOPT_WRITEFUNCTION 回调函数的名称,其中回调函数采用两个参数。第一个是 cURL 资源,第二个是包含要写入的数据的字符串。必须使用此回调函数保存数据。它必须返回写入的确切字节数,否则传输将因错误而中止。

所以,这意味着一个响应可以被分割成几块数据。为了正确接收前 20000 个字节,您必须添加 $full_length 计数器:

$full_length = 0;
function receiveResponse($ch,$string) use (&$full_length) {
    $length = strlen($string);
    $full_length += $length;
    if($full_length >= 20000) { return -1; }
    return $length;
}

Lets look at option description from this manual http://www.php.net/manual/en/function.curl-setopt.php:

CURLOPT_WRITEFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by using this callback function. It must return the exact number of bytes written or the transfer will be aborted with an error.

So, it means what a response can be split into several pieces of data. For appropriate receiving of first 20000 bytes you must add $full_length counter:

$full_length = 0;
function receiveResponse($ch,$string) use (&$full_length) {
    $length = strlen($string);
    $full_length += $length;
    if($full_length >= 20000) { return -1; }
    return $length;
}
仅一夜美梦 2024-12-08 00:43:31

尝试评论这个curl_setopt($ch, CURLOPT_FILE, $fh);

try comment this curl_setopt($ch, CURLOPT_FILE, $fh);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文