在循环中使用cURL

时间:2013-05-04 06:21:14

标签: php loops curl

我正在编写一个脚本,其中需要通过cURL请求将未指定数量的文件上传到远程API。但是,此脚本会挂起并最终超时。奇怪的是,所有请求都成功(文件成功上传),但脚本无法继续。这是循环:

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

我相信这与循环有关。我尝试在循环中添加curl_close,但它没有解决问题。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

timeout放入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);
}

答案 1 :(得分:-1)

通过调用下面的函数

从循环中分离出卷曲
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);
}