如何在php中进行非阻塞调用

时间:2012-01-14 18:48:32

标签: php curl exec

我使用php脚本上传大量文件。我正在使用CURL命令。远程服务器仅接受POST请求。但是当我执行下面的脚本时,它处理第一个请求并等待直到第一个文件上传。有没有办法让它不阻塞并同时运行2个卷曲上传请求。找到下面的代码示例。

<?php
  $arr= array(somefile1.txt,somefile2.txt);
  for ( $i=0;$i<2;$i++) {
     $cmd = "curl  -F name=aaa -F type=yyy  FileName=@/xxxxx/xxxx/$arr[$i] http://someurl.com";
     print "Executing file ";
     shell_exec("nohup  $cmd  2> /dev/null & echo $!" );
     print "=======  done ================";
  }
?>

4 个答案:

答案 0 :(得分:5)

我相信你可能需要curl_multi_init。这是一个出站示例;它必须适应您的入站问题。这似乎比你自己分叉多个线程更清晰。

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

答案 1 :(得分:2)

有一篇关于“多线程”的好文章,请在此处查看:Multithreading in PHP with CURL

答案 2 :(得分:0)

您可以尝试使用 PHP Simple Curl Wrapper - https://github.com/Graceas/php-simple-curl-wrapper。该库允许异步处理多个请求。

您可以在这里找到完整的答案:php asynchronous cURL request

答案 3 :(得分:-1)

不,你不能同时运行两个卷曲声明。

卷曲是为了像这样工作。 Curl语句将生成后面的语句 等到它完成它的操作。