stop a curl transfer in the middle

2019-07-10 16:39发布

i could only think of curl_close() from one of the callback functions. but php throws a warning:

PHP Warning: curl_close(): Attempt to close cURL handle from a callback.

any ideas how to do that?

3条回答
三岁会撩人
2楼-- · 2019-07-10 16:56

If the problem is that is taking too long to execute the curl, you could set a time, example

<?php
$c = curl_init('http://slow.example.com/');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 15);
$page = curl_exec($c);
curl_close($c);
echo $page;
查看更多
\"骚年 ilove
3楼-- · 2019-07-10 17:01

you can return false or something what is not length of currently downloaded data from callback function to abort curl

查看更多
干净又极端
4楼-- · 2019-07-10 17:13

I had a similar problem that needed me to be able to stop a curl transfer in the middle. This is easily in my personal top ten of 'dirty hacks that seem to work' of all time.

Create a curl read function that knows when it's time to cancel the upload.

function curlReadFunction($ch, $fileHandle, $maxDataSize){

    if($GLOBALS['abortTransfer'] == TRUE){
        sleep(1);
        return "";
    }
    return fread($fileHandle, $maxDataSize);
}

And tell Curl to stop if the data read rate drops too low for a certain amount of time.

curl_setopt($ch, CURLOPT_READFUNCTION, 'curlReadFunction');
curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 1024);
curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, 5);

This will cause the curl transfer to abort during the upload. Obviously not ideal but it seems to work.

查看更多
登录 后发表回答