我正在编写一个脚本,其中需要通过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,但不能解决问题.有任何想法吗?
解决方法:
在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);
}