David Jones
David Jones

Reputation: 10239

Using cURL in a loop

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?

Upvotes: 3

Views: 3912

Answers (2)

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

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

Upvotes: 4

Amir
Amir

Reputation: 4111

seperate curl from loop with calling a function like below

foreach ($paths as $path) {
call_curl($path);
}


function call_curl($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);
}

Upvotes: -1

Related Questions