Php wait for response

How to make asynchronous HTTP requests in PHP ?

Asynchronous HTTP request helps us to process HTTP requests using non-blocking input or output, in different threads. Some refer to it as COMET capabilities. The main use of Asynchronous HTTP requests is when the client is requesting the server for a late response. A common example is an AJAX chat client where we push or pull from both the client and the server. These scenarios block the client for quiet a long time on the server’s socket waiting for a new message.

PHP serves requests synchronously. It means that each line of code executes in the synchronous manner of the script. After getting the result from one line it executes next line or wait for the result before jumping to the execution of the next line of code. There are cases where we are supposed to make requests to URLs and they do not rely on each other. In this scenario we do not want to wait for the result from one request to execute other requests. Therefore, we make asynchronous requests.

Guzzle 6: Guzzle is a PHP HTTP client helps to send the HTTP requests.These methods can be used to send the asynchronous HTTP requests.

  • RequestAsync,
  • SendAsync,
  • GetAsync,
  • HeadAsync,
  • PutAsync,
  • PostAsync,
  • DeleteAsync,
  • patchAsync

Download Guzzle php package.Can be installed through composer.

php composer.phar require guzzlehttp/guzzle:~6.0
composer require guzzlehttp/guzzle:~6.0

Please include the “autoload” file in the script part of the code so that it loads all the classes and methods.

Читайте также:  Python web server on raspberry pi

PHP

In the above code, the “autoload” file is included, and then the Guzzle Http client object is created which is stored in the “client” variable and for each Http request getAsync() method is used with the URL. The request getting the first response will print the number. The order of the request will not matter.

Asynchronous HTTP requests using Promise: A single result of an asynchronous operation represents a Promise. Asynchronous requests are used in the non-blocking of the HTTP operations. When asynchronous HTTP requests send a promise, it gets returned.

Execute a request using HTTPlug:

$request = $messageFactory->createRequest( 'GET', 'http://php-http.org'); $promise = $client->sendAsyncRequest($request); echo 'Non-blocking!';

Wait: The “promise” which is returned from the above, implements http\Promise\Promise. The response is not known yet during this point of time. Wait for that response to arrive.

try < $response = $promise->wait(); > catch (\Exception $exception) < echo $exception->getMessage(); >

Then: Instead of waiting, we can perform steps asynchronously. Call the then method with two arguments.

  1. One callback that will be executed if the request turns out to be successful.
  2. Callback that will be executed if the request results in an error.

// Success Callback function (ResponseInterface $response) < echo 'New response!'; // Write status code to the log file file_put_contents('responses.log', $response->getStatusCode() . «\n», FILE_APPEND); return $response; >, // Failure Callback function (\Exception $exception)

Concurrency in Promise: Concurrency means multiple computations taking place at the same time. It is good when we deal with a lot of request at the same time. For concurrency, we must use “EachPromise” class and yield generator and at last add wait() to the end of the program.

Источник

PHP — Wait for response

I’m having simple script which comunicate via REST with some server. Server architecture have some holes, and I fight with one of them right now. When I send one request to assign some profile and don’t wait for response and send second request. It basicly just scrap the first request and do the second one only. My code looks like:

$this->assignProfile($token, $id, FIRST); $this->assignProfile($token, $id, SECOND); 
public function assignProfile($token, $organizationId, $profileId) < //define enviroment and path $host = enviroment; $path = "/admin/members/".$organizationId."/assigned-profiles"; $data_string = '["'.$profileId.'"]'; // set up the curl resource $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $host.$path); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer '.$token.'', 'Content-Length: ' . strlen($data_string) )); echo "
OK
"; // execute the request $output = curl_exec($ch); curl_close($ch); >

The thing is, webservice is not response with any body or something, it just response with code 200. How can I code this to wait for a 200 and than continue with second request.

Источник

Does php wait for a response from an API call? [closed]

It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.

How is the best way to call an external domain from within a php script. Is it curl ? And if so does php wait for the line to be processed before moving on so that we can be sure of the return data.

3 Answers 3

The easeiest way to get a response from an external URL is to use file_get_contents(), but cURL is definitely the better way if you want to have more options or send post data. Both of these functions wait for the response, though. PHP is pretty straight forward.

Actually, there’re few workarounds to make asynchronous requests and also experimental library pthreads.

if you’re using curl, then you’d wanna set the curl timeout option to prevent excessive hanging. e.g. curl_setopt($curl, CURLOPT_TIMEOUT, 5); //allow 5 secs

You can either use Curl, file_get_contents (with the appropriate extensions loaded) or do some socket work.

class Tools < public static function post_request($url, $datos) < $resultado=null; $datos=http_build_query($datos); $url=parse_url($url); // extract host and path: $host=$url['host']; $ruta=$url['path']; $socket=fsockopen($host, 80, $errno, $errstr, 30); if($socket) < // send the request headers: fputs($socket, "POST $ruta HTTP/1.1\r\n"); fputs($socket, "Host: $host\r\n"); fputs($socket, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($socket, "Content-length: ". strlen($datos) ."\r\n"); fputs($socket, "Connection: close\r\n\r\n"); fputs($socket, $datos); while(!feof($socket)) < $resultado.= fgets($socket, 128); >> else die('ERROR'); fclose($socket); $resultado=explode("\r\n\r\n", $resultado, 2); $header=isset($resultado[0]) ? $resultado[0] : ''; $contenido=isset($resultado[1]) ? $resultado[1] : ''; return array( 'status' => 'ok', 'header' => $header, 'content' => $contenido ); > >; 

If I remember correctly, the script won’t proceed until the request is processed.

Источник

PHP how to wait for data

Following Google documentation to create a request (link) using PHP, but received an empty response <> within 1 sec. I tried to use another language to send the same request, it takes about 10 secs to receive a correct response. I tried to comment out CURLOPT_POSTFIELDS => $json and I can get an error response of POST requests require a Content-length header . Wondering am I missing something in below codes?

 >, "features":[ < "type":"LOGO_DETECTION", "maxResults":1 >] > ] >'; $json = json_decode($str, true); // Get cURL resource $curl = curl_init(); // Set some options - we are passing in a useragent too here curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'https://vision.googleapis.com/v1/images:annotate?key=kkkkkkeeeeeyyyyy', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $json )); // Send the request & save response to $resp $resp = curl_exec($curl); echo $resp; ?> 

EDIT If I use curl in terminal and I save the str in .json file, I can get the correct result. Request in terminal

curl -v -s -H "Content-Type: application/json" https://vision.googleapis.com/v1/images:annotate?key= kkkkkkeeeeeyyyyy --data-binary @request.json 
* Trying 172.217.24.202. * Connected to vision.googleapis.com (172.217.24.202) port 443 (#0) * ALPN, offering http/1.1 * Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH * successfully set certificate verify locations: * CAfile: /Users/pakhocheung/anaconda/ssl/cacert.pem CApath: none * TLSv1.2 (OUT), TLS header, Certificate Status (22): * TLSv1.2 (OUT), TLS handshake, Client hello (1): * TLSv1.2 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Client hello (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS change cipher, Client hello (1): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-ECDSA-AES128-GCM-SHA256 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=*.googleapis.com * start date: Oct 24 08:38:00 2017 GMT * expire date: Dec 29 00:00:00 2017 GMT * subjectAltName: host "vision.googleapis.com" matched cert's "*.googleapis.com" * issuer: C=US; O=Google Inc; CN=Google Internet Authority G2 * SSL certificate verify ok. > POST /v1/images:annotate?key=AIzaSyBFPRLC8BEtYPdfgg3B_aadpmKFRtfENbE HTTP/1.1 > Host: vision.googleapis.com > User-Agent: curl/7.49.0 > Accept: */* > Content-Type: application/json > Content-Length: 318 > * upload completely sent off: 318 out of 318 bytes < HTTP/1.1 200 OK < Content-Type: application/json; charset=UTF-8 < Vary: X-Origin < Vary: Referer < Date: Tue, 07 Nov 2017 04:13:12 GMT < Server: ESF < Cache-Control: private < X-XSS-Protection: 1; mode=block < X-Frame-Options: SAMEORIGIN < X-Content-Type-Options: nosniff < Alt-Svc: quic=":443"; ma=2592000; v="41,39,38,37,35" < Accept-Ranges: none < Vary: Origin,Accept-Encoding < Transfer-Encoding: chunked < < "responses": [ < "logoAnnotations": [ < "mid": "/m/045c7b", "description": "Google", "score": 0.34495986, "boundingPoly": < "vertices": [ < "x": 72, "y": 53 >, < "x": 400, "y": 53 >, < "x": 400, "y": 164 >, < "x": 72, "y": 164 >] > > ] > ] > 

Источник

Оцените статью