How to create asynchronous HTTP request in PHP

  5 months ago     Views:  474  
Julius Braun
1 Follows


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.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

5 Comments

  • Image
    Phoebe
    September 25, 2020 Reply

    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

  • Image
    Erna
    September 04, 2020 Reply

    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/

  • Image
    Emilia
    August 22, 2020 Reply

    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/

  • Image
    007카지노
    May 21, 2020 Reply

    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

  • Image
    Reva
    May 18, 2020 Reply

    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/