1

I wanted to make 1500 Asynchronous request in PHP. I tried the following code but want to know that if its async or not ? What is a correct way to make async request in PHP

function test($url){

    $data = file_get_contents($url);
    if(!empty($data)){
        echo "Success";
    }
    else{
        echo "Fail";
    }
}
for ($i=0; $i < 1500; $i++ ) { 
    $data = 'https://example.com';
    test($data);
}
Usama Iftikhar
  • 183
  • 2
  • 14

3 Answers3

2

file_get_contents is not an asynchronous request. It is a 'blocking' request. You will not move past that line until it either succeeds of fails.

One way to make an async request in php is to use the ability of the operating system to fork a process. Another is to use sockets (and write to the socket without waiting on a response). A third is to use pthreads. These are all 'tricks' and not really async at all, however pthreads and forking will simulate an async request fairly well. The following code uses the fork technique.

<?php
private function request($url, $payload) {
  $cmd = "curl -X POST -H 'Content-Type: application/json'";
  $cmd.= " -d '" . $payload . "' " . "'" . $url . "'";
  if (!$this->debug()) {
    $cmd .= " > /dev/null 2>&1 &";
  }
  exec($cmd, $output, $exit);
  return $exit == 0;
}
?>

This code was taken from a great article on the subject that can be found here:

https://segment.com/blog/how-to-make-async-requests-in-php/

The writer of the article does not discuss threading, but forking the process is simply using the OS to create your threads for you rather than doing it within your code. (sort of....)

Mark C.
  • 378
  • 1
  • 12
1

No this is synchronous. 1 request will happen at a time.

The easiest way to do asynchronous HTTP requests it to use a HTTP library that supports it, or curl_multi_* functions.

Evert
  • 93,428
  • 18
  • 118
  • 189
0

PHP does not provide Async execution by default.

So your code can not send a Async request. Above code sample will send 1500 requests one after another. It will keep process halted until all requests have been made.

You can try pthreads (http://php.net/manual/en/book.pthreads.php) for this purpose or multi curl (http://php.net/manual/en/function.curl-multi-init.php).

try to be assured if your use case really needs Async requests.

hanish singla
  • 782
  • 8
  • 21