如何在php中进行非阻塞调用
我正在使用 php 脚本上传大量文件。我正在使用 CURL 命令。远程服务器仅接受 POST 请求。但是当我执行下面的脚本时,它会处理第一个请求并等待第一个文件上传。有没有办法使其非阻塞并同时运行 2 个curl 上传请求。找到下面的代码示例。
<?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 ================";
}
?>
I am using a php script to upload lot of files. I am using the CURL command . The remote server accepts only POST requests. But when I execute the below script it processes the first request and waits until the first file is uploaded. Is there a way to make it non blocking and run simultaneous 2 curl upload requests .Find the code sample below.
<?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 ================";
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信您可能需要 curl_multi_init。这是一个出站示例;它必须针对您的入站问题进行调整。这看起来比你自己分叉多个线程更干净。
I believe you may want curl_multi_init. Here is an outbound example; it will have to be adapted for your inbound problem. This seems cleaner than you forking multiple threads yourself.
有一篇关于“多线程”的好文章,请在这里查看:使用 CURL 在 PHP 中实现多线程
There is a good article about "multithreading", take a look at it here: Multithreading in PHP with CURL
您可以尝试使用 PHP Simple Curl Wrapper - https://github.com/Graceas/php -简单卷曲包装器。该库允许异步处理多个请求。
您可以在这里找到完整的答案:php异步cURL请求
You can try use PHP Simple Curl Wrapper - https://github.com/Graceas/php-simple-curl-wrapper. This library allows the processing of multiple request's asynchronously.
You can find full answer here: php asynchronous cURL request
不,您不能同时运行两个curl 语句。
Curl 就是为这样的工作而生的。 Curl 语句将做出后面的语句
等到它完成操作。
No you cannot run simultaneously two curl statements.
Curl is made for working like this. A Curl statement will make the later statements
wait until it finishes its operation.