PHP CURLOPT_WRITEFUNCTION似乎不工作 [英] PHP CURLOPT_WRITEFUNCTION doesn't appear to be working

查看:1542
本文介绍了PHP CURLOPT_WRITEFUNCTION似乎不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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



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

  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);

但是,流只是继续写入文件,文件大小越来越大。



我做错了可怕的错误?



注意,

解决方案

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


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


被分割成几个数据段。为了适当接收前20000字节,必须添加$ full_length计数器:

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


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.

Am i doing something horribly wrong?

Regards,

解决方案

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;
}

这篇关于PHP CURLOPT_WRITEFUNCTION似乎不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆