PHP asynchronous cURL with callback

I am trying to execute a query using cURL asynchronously with a callback. I use a piece of code that I copy from the site.

When I write this url in my browser: http: //www.myhost: 3049 / exemplo / index / async / , it executes the asyncAction function, which executes the curl_post function.

/** * Send a POST requst using cURL * @param string $url to request * @param array $post values to send * @param array $options for cURL * @return string */ function curl_post($url, array $post = NULL, array $options = array()) { $defaults = array( CURLOPT_POST => 1, CURLOPT_HEADER => 0, CURLOPT_URL => $url, CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 4, CURLOPT_POSTFIELDS => http_build_query($post) ); $ch = curl_init(); curl_setopt_array($ch, ($options + $defaults)); if( ! $result = curl_exec($ch)) { $result = curl_error($ch); } curl_close($ch); return $result; } public function asyncAction() { $this->curl_post("http://www.myhost:3049/exemplo/index/add/"); } 

Then cURL performs cURL with this URL to perform an action that NOW is in the same class as the rest of the functions, just for testing. This is an addAction action that simply returns a string with the message "CALLBACK".

 function addAction() { sleep(15); return "CALLBACK"; } 

The result of $ returns only false. Perhaps the problem is that I ask you to try to perform an action that is in the same class as the cURL function. But anyway, how can I get an error message. Is there a better solution, tested and with a good explanation about using as asynchronous with callback? Because the things you read are poorly explained, and also do not explain when, how to manage the callback.

+6
source share
1 answer

Maybe take a look at this: https://gist.github.com/Xeoncross/2362936

Request:

 class Requests { public $handle; public function __construct() { $this->handle = curl_multi_init(); } public function process($urls, $callback) { foreach ($urls as $url) { $ch = curl_init($url); curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => TRUE)); curl_multi_add_handle($this->handle, $ch); } do { $mrc = curl_multi_exec($this->handle, $active); if ($state = curl_multi_info_read($this->handle)) { //print_r($state); $info = curl_getinfo($state['handle']); //print_r($info); $callback(curl_multi_getcontent($state['handle']), $info); curl_multi_remove_handle($this->handle, $state['handle']); } usleep(10000); // stop wasting CPU cycles and rest for a couple ms } while ($mrc == CURLM_CALL_MULTI_PERFORM || $active); } public function __destruct() { curl_multi_close($this->handle); } } 
+8
source

Source: https://habr.com/ru/post/975834/


All Articles