Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cURL in a loop

Tags:

loops

php

curl

I'm writing a script in which an unspecified number of files need to be uploaded via cURL requests to a remote API. However, this script hangs and eventually times out. Strangely enough, all the requests are successful (the files are successfully uploaded), but the script is unable to continue. Here's the loop:

foreach ($paths as $path) {
  $ch = curl_init($path);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Token: '.$token, 'Content-Length: '.filesize($path));
  curl_setopt($ch, CURLOPT_PUT, true);
  curl_setopt($ch, CURLOPT_INFILE, fopen($path, 'r'));
  curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path));
  echo curl_exec($ch);
}

I believe this has something to do with the loop. I've tried adding curl_close within the loop, but it doesn't solve the problem. Any ideas?

like image 399
David Jones Avatar asked Sep 01 '26 16:09

David Jones


1 Answers

put timeout in CURL

foreach ($paths as $path) {
  $ch = curl_init($path);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Token: '.$token, 'Content-Length: '.filesize($path));
  curl_setopt($ch, CURLOPT_PUT, true);
  curl_setopt($ch, CURLOPT_INFILE, fopen($path, 'r'));
  curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path));
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
  curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
  echo curl_exec($ch);
}
like image 174
Yogesh Suthar Avatar answered Sep 03 '26 04:09

Yogesh Suthar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!