Fire and forget HTTP requests in PHP

Chris White, on creating really fast HTTP requests in PHP, by manually building an HTTP request and sending a payload:

Hand-crafting HTTP requests seemed like an unreliable method at first, but after some pretty extensive testing I can vouch for it reliably sending the requests and the remote server receiving them in full. It can be tricky to craft the request properly (respecting the line feeds that the HTTP specification expects, etc), but that’s why you have tests, right? 🙂

Like so:

$endpoint = 'https://logs.loglia.app';
$postData = '{"foo": "bar"}';

$endpointParts = parse_url($endpoint);
$endpointParts['path'] = $endpointParts['path'] ?? '/';
$endpointParts['port'] = $endpointParts['port'] ?? $endpointParts['scheme'] === 'https' ? 443 : 80;

$contentLength = strlen($postData);

$request = "POST {$endpointParts['path']} HTTP/1.1\r\n";
$request .= "Host: {$endpointParts['host']}\r\n";
$request .= "User-Agent: Loglia Laravel Client v2.2.0\r\n";
$request .= "Authorization: Bearer api_key\r\n";
$request .= "Content-Length: {$contentLength}\r\n";
$request .= "Content-Type: application/json\r\n\r\n";
$request .= $postData;

$prefix = substr($endpoint, 0, 8) === 'https://' ? 'tls://' : '';

$socket = fsockopen($prefix.$endpointParts['host'], $endpointParts['port']);
fwrite($socket, $request);
fclose($socket);

This way of requesting performs about 5 times faster than making requests using Guzzle. No surprise there really: the closer you are to the core language, the faster it will work. C is faster than PHP. PHP’s built-in functions are faster than libraries built on top.

Fire and forget HTTP requests in PHP →

💁‍♂️ Back when I was a lecturer Web we started off with looking at the HTTP protocol before we even wrote one single line of PHP. Mandatory knowledge for everyone working in web imho.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.