PHP cURL同步和异步

编程入门 行业动态 更新时间:2024-10-18 01:35:09
本文介绍了PHP cURL同步和异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在项目中使用PHP cURL,在这种情况下,我需要通过cURL发送数据并等待响应(并延迟所有代码,直到在cURL请求中收到响应为止)-同步请求,而我还希望在不同的情况下异步发送数据,而不是等待cURL请求完成.

I want to use PHP cURL in a project and in a scenario I need to send the data via cURL and wait for a response (and delay all code until a response is received in the cURL request) - sync request, and I also want in a different scenario to send the data async and not wait for the cURL request to be completed.

是否存在可用于发送数据ASYNC而不等待目标URL的响应继续执行代码的cURL参数或函数?

Is there a cURL parameter or function that I can use to send the data ASYNC and not wait for the response from the target URL to continue the code execution?

这是我现在的代码,默认情况下,请求是同步的,脚本等待,直到从目标URL发送响应为止.

Here's my code for now, and the request is sync, by default, and the script waits until a response from the target URL is sent.

$ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_POSTFIELDS,$data); $result = curl_exec($ch); curl_close($ch);

我的应用程序有两种情况:

My application has two scenarios:

1)需要将数据传递到辅助服务器,并且一旦确认服务器已接收到该数据,就继续在我的应用程序中执行代码;

1) Data needs to be passed to a secondary server and once there is a confirmation that the server received it, continue the code execution in my application;

2)数据已传递到辅助服务器,但是传递的信息不是那么重要,因此我们无需等待服务器确认接收到该信息就可以继续. 谢谢

2) Data is passed to a secondary server, but the information passed is not so important, therefore we do not need to wait for a confirmation that the server received it, in order to continue. Thank you

推荐答案

以下是PHP 关于如何异步使用curl的文档:

<?php // create both cURL resources $ch1 = curl_init(); $ch2 = curl_init(); // set URL and other appropriate options curl_setopt($ch1, CURLOPT_URL, "lxr.php/"); curl_setopt($ch1, CURLOPT_HEADER, 0); curl_setopt($ch2, CURLOPT_URL, "www.php/"); 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); ?>

更多推荐

PHP cURL同步和异步

本文发布于:2023-06-06 00:34:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/531174.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PHP   cURL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!