Zakukashi
Zakukashi

Reputation: 586

How to handle interrupts or completed with cURL

My php script downloads files from a remote server using cURL. I wanted to monitor the bandwidth that was being used when downloading the file so what I did was put an SQL update query within the write_callback function. This works like a charm but im worried that the database will have troubles if a script like this is updating data every 10 miliseconds or so. Does cURL have a "completed" call back function? so that the script will collect the amount of bytes that were downloaded then update ONLY once when its been completed? And also does the cURL have some type of interruption callback or incomplete? so when users kill the download it somehow recognizes that and subtracts the bytes that were downloaded in the process.

Upvotes: 2

Views: 689

Answers (1)

DaveRandom
DaveRandom

Reputation: 88657

You could do something like this:

$ch = curl_init($url);

// ... set whatever options you need

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $data) {
  global $bytes;
  $bytes += strlen($data);
  // Write data here
});

$bytes = 0;
$starttime = microtime(TRUE);

curl_exec();

$endtime = microtime(TRUE);
$totaltime = $endtime - $starttime;

// You would do your DB update here
echo "Downloaded $bytes bytes in $totaltime seconds (".($bytes / $totaltime)." bytes/second)";

Handling interupts would be more difficult, but maybe you could use register_shutdown_function()? I don't know if this actually gets called when the script receives SIGINT, though. You may also be able to use pcntl_signal() if it is available.

Upvotes: 1

Related Questions