How to create asynchronous HTTP request in PHP

While creating HTTP request to other websites,  sometimes we don't need to get response from the server. In this case we have to just send the HTTP request and should drop the connection, so we don't wait until request complete and complete the next process.

This can be done from using sockets if we don't need to check about the response from the request. This is because socket connection can be terminated straight after sending the request without waiting. This is like fire and forget the request.

To use the socket connection, there is fsockopen() function in PHP. I have used this function to send the HTTP request.

Here is my full code to send HTTP request.

/**
 * Send a HTTP request, but do not wait for the response
 *
 * @param string $method The HTTP method
 * @param string $url The url (including query string)
 * @param array $params Added to the URL or request body depending on method
 */
public function sendRequest(string $method, string $url, array $params = []): void
{
    // url check
    $parts = parse_url($url);
    if ($parts === false)
        throw new Exception('Unable to parse URL');
    $host = $parts['host'] ?? null;
    $port = $parts['port'] ?? 80;
    $path = $parts['path'] ?? '/';
    $query = $parts['query'] ?? '';
    parse_str($query, $queryParts);

    if ($host === null)
        throw new Exception('Unknown host');
    $connection = fsockopen($host, $port, $errno, $errstr, 30);
    if ($connection === false)
        throw new Exception('Unable to connect to ' . $host);
    $method = strtoupper($method);

    if (!in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
        $queryParts = $params + $queryParts;
        $params = [];
    }

    // Build request
    $request  = $method . ' ' . $path;
    if ($queryParts) {
        $request .= '?' . http_build_query($queryParts);
    }
    $request .= ' HTTP/1.1' . "\r\n";
    $request .= 'Host: ' . $host . "\r\n";

    $body = http_build_query($params);
    if ($body) {
        $request .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
        $request .= 'Content-Length: ' . strlen($body) . "\r\n";
    }
    $request .= 'Connection: Close' . "\r\n\r\n";
    $request .= $body;

    // Send request to server
    fwrite($connection, $request);
    fclose($connection);
}

With this function, you can simply send asynchronous HTTP request. If you have any suggestions please make comment bellow, would be much appreciated.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

7 Comment

SA
Chas
December 23, 2020

Keep this going please, great job!cheap nfl jerseys Chinahttp://www.wollfraktion.de/phorum/read.php?16,64967http://PistDorSt.mihanblog.com/post/457

SA
Maddison
October 10, 2020

Hmm it seems like your blog ate my first comment (it was super long)
so I guess I'll just sum it up what I had written and say, I'm thoroughly enjoying your blog.
I too am an aspiring blog blogger but I'm
still new to everything. Do you have any points for rookie blog writers?
I'd genuinely appreciate it.wholesale nhl jerseys from Chinahttps://online-wiki.win/index.php?title=2011_Nfl_Football_Schedule_Saints_V_Packers_Odds_Prediction_2391231031&oldid=178517https://record-wiki.win/index.php?title=2013_Bcs_National_Championship_Notre_Dame_Vs_Alabama_Prop_Be_1391365556&oldid=196596

SA
Phoebe
September 25, 2020

This page truly has all of the information and facts I
wanted about this subject and didn't know who to ask.
cheap mlb jerseys Chinahttp://korijtkw.mee.nu/?entry=3080320http://atlantis.co.ao/index.php/forum/welcome-mat/352191-7-expanding-techie-fads-which-happen-to-be-swappin

SA
Erna
September 04, 2020

Thanks for ones marvelous posting! I genuinely enjoyed reading it, you can be a great author.
I will always bookmark your blog and will often come back later on. I want
to encourage yourself to continue your great posts,
have a nice afternoon!wholesale hockey jerseys free shipping from Chinahttps://sierra-wiki.win/index.php?title=Nfl_Kickoff_Has_Giants_Defending_Title_Vs_Redskins_4481111331&oldid=178554http://orionjr533ft.ek1.pl/2020/08/11/klopp-will-require-gatwick/

SA
Emilia
August 22, 2020

Thanks for one's marvelous posting! I actually enjoyed reading it, you
may be a great author. I will be sure to bookmark your
blog and will come back at some point. I want to encourage you continue your great posts,
have a nice morning!wholesale baseball jerseys Chinahttp://emilianozohf331.unblog.fr/2020/08/07/in-times-past-answerable/http://emilianozohf331.unblog.fr/2020/08/07/in-times-past-answerable/

SA
007카지노
May 21, 2020

If you are going for finest contents like myself, only pay a quick visit this
web page every day because it provides feature
contents, thanks http://uricasino114.com

SA
Reva
May 18, 2020

I needed to thank you for this excellent read!! I
definitely loved every bit of it. I have you
book-marked to look at new stuff you Ahaa, its good dialogue on the
topic of this piece of writing here at this blog, I have
read all that, so now me also commenting at this place.
I couldn't resist commenting. Exceptionally well written! http://car.com/