Как отправить запрос PHP и не дожидаться ответа (How to make asynchronous POST with PHP)

(blocks/api/class/sub_blocks/async/test_get_beakon_php.php)

Пример запроса в коде:

print ($start = floor(microtime(true) * 1000) . '</br>');
$url = "/blocks/api/class/sub_blocks/async/handler.php";


   // Создаем cURL-сессию
   $ch = curl_init();
   // Устанавливаем URL и другие параметры
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   // curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Устанавливаем таймаут в 5 секунд
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 15); // Установка таймаута в 100 миллисекунд

   // Выполняем запрос
   $response = curl_exec($ch);
   if ($response === false) {
       // Обработка ошибки
   } else {
       // Обработка успешного ответа
   }
   // Закрываем сессию
   curl_close($ch);
 

print ($finish = floor(microtime(true) * 1000) . '<br>');

print ($start - $finish);

(blocks/api/class/sub_blocks/async/handler.php)

Пример handler.php:

// Отправляем ответ клиенту немедленно
ob_start();
header("Connection: close");
header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();

// Сохраняем данные в журнале или базе данных
$logData = array(
   'timestamp' => time(), // текущее время
   'page' => $_SERVER['REQUEST_URI'], // текущий URL-адрес страницы
   'get_params' => $_GET // GET-параметры запроса
);


sleep(5);
 

 

***

 

Альтернативный вариант:

(первый вариант работает отлично, этот оставлю на потом)

There are several ways to make a async call with PHP. I will describe in this post how to Asynchronous POST a PHP Array to a php script with cURL making a "fire and forget" call, meaning that we will post the data and we will not wait for a result. In our example, we will post the $_SERVER array to a script in another page without waiting to see what the script is doing. We are going to need two files, the first will be named async.php and the second will be the handler.php which will handle the array we will post. Let me give you the code at this point and will talk about it later on.  the async.php file

&lt;?php $fields = $_SERVER;   $curl_options = array( CURLOPT_URL =&gt; "http://127.0.0.1/handler.php", CURLOPT_POST =&gt; 1, CURLOPT_POSTFIELDS =&gt; http_build_query( $fields ), CURLOPT_HTTP_VERSION =&gt; 1.0, CURLOPT_HEADER =&gt; 0, CURLOPT_TIMEOUT =&gt; 1 );   $curl = curl_init();curl_setopt_array( $curl, $curl_options ); $result = curl_exec( $curl );curl_close( $curl ); echo "I am echoing out since I am not waiting for a result"; ?&gt;

the handler.php file

&lt;?php   ob_end_clean();ignore_user_abort();ob_start();header("Connection: close");header("Content-Length: " . ob_get_length());ob_end_flush();flush();   sleep(5);   $user_agent = $_POST['HTTP_USER_AGENT'];   $visitor_ip = $_POST['REMOTE_ADDR'];   $tomail = "User Agent :".$user_agent."\r\nVisitor IP : ".$visitor_ip;mail('info@tsartsaris.gr', 'curl test', $tomail);   ?&gt;

 In the async.php file we prepare to POST the array with cURL. Assigning the $_SERVER array to $fields, which will be used in the cURL options. With http_build_query we take the $fields array and we create a URL-encoded query string to pass to cURL. The critical part in the cURL options array is the CURLOPT_TIMEOUT that we set to 1. What we do is posting the data and after one (1) second we close the connection not waiting for an answer. Then we echoing something just to be sure the connection is closed. 

    In the handler.php first seven (7) lines, until flush(); are for the connection handling. In the most simple way I can describe it is that we say to php "Even thought the connection with the one who posted the data lost or closed, go on to complete the job". Read more about Connection handling. After that just for the scientific evidence we tell the script to sleep for 5 seconds and then sent an email with some data. 

    So if we go and visit the async.php it will post the array with curl, close the connection with the handler.php after 1 second and then echo our text. The handler.php will deal with the closed connection as it never happened, will wait for 5 seconds and then it will email us the data we want. Remember to change the mail address with yours please.

Источники:

http://www.tsartsaris.gr/how-to-make-asynchronous-post-with-php (сайт не работает)

https://web.archive.org/web/20160302032136/http://www.tsartsaris.gr/how-to-make-asynchronous-post-with-php

https://qna.habr.com/q/248459

Связаться с автором

Комментарии

Если у вас есть вопрос, критика или другое мнение - напишите в комментариях.