PHP
HTTP requests
asynchronous requests
non-blocking HTTP
PHP programming

How to make HTTP requests in PHP and not wait on the response

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In this article, we will explore how to make HTTP requests in PHP without waiting for a response. This method is valuable for improving application performance when the response itself is not required immediately or at all, such as logging, analytics tracking, or firing off background jobs in a web application. We'll dive into techniques that achieve this non-blocking functionality and provide comprehensive examples.

Making Non-Blocking HTTP Requests

When we talk about non-blocking HTTP requests in PHP, we refer to the process of initiating a request and then proceeding with other tasks without waiting for the request to complete. There are multiple methods to achieve non-blocking HTTP requests, and we'll cover the most common ones below.

1. Using fsockopen

The fsockopen function can be used to open an internet protocol connection (HTTP, HTTPS, etc.) and send a request. By setting the stream options to non-blocking, you can send requests asynchronously.

Example:

php
1function sendAsyncRequest($host, $path, $data = []) {
2    $requestData = http_build_query($data);
3    $fp = fsockopen($host, 80, $errno, $errstr, 30);
4
5    if (!$fp) {
6        echo "Error: $errno - $errstr
\n";
7        return;
8    }
9    
10    $out = "POST $path HTTP/1.1\r\n";
11    $out .= "Host: $host\r\n";
12    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
13    $out .= "Content-Length: " . strlen($requestData) . "\r\n";
14    $out .= "Connection: Close\r\n\r\n";
15    $out .= $requestData;
16    
17    fwrite($fp, $out);
18    fclose($fp);
19}
20
21sendAsyncRequest('www.example.com', '/api/endpoint', ['param' => 'value']);

In this example, the request method is HTTP POST, and the stream is closed immediately after sending the data, ensuring non-blocking behavior.

2. Using curl with Non-Blocking Options

Curl is another prominent tool for sending HTTP requests in PHP. By using certain options, you can prevent the script from waiting for the server's response.

Example:

php
1function curlNonBlocking($url, $data) {
2    $ch = curl_init();
3
4    curl_setopt($ch, CURLOPT_URL, $url);
5    curl_setopt($ch, CURLOPT_POST, 1);
6    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
7    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
8    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
9    curl_setopt($ch, CURLOPT_HEADER, false);
10
11    curl_exec($ch);
12    curl_close($ch);
13}
14
15curlNonBlocking('http://www.example.com/api/endpoint', ['param' => 'value']);
  • CURLOPT_RETURNTRANSFER is set to false so that the call does not wait for any data.
  • CURLOPT_TIMEOUT_MS is set to a small value to ensure that the script times out before waiting for a response.

3. Using exec for Command-Line HTTP Requests

If you have access to command-line tools like wget or curl, you can execute them in the background.

Example using exec:

php
$url = 'http://www.example.com/api/endpoint';
$data = http_build_query(['param' => 'value']);
exec("curl -X POST -d \"$data\" \"$url\" > /dev/null 2>&1 &");

By redirecting the output to /dev/null and appending &, this command runs the HTTP request in the background.

Key Considerations

When implementing non-blocking HTTP requests, consider the following:

  • Error Handling: Non-blocking requests may fail silently; ensure you log errors or failures effectively.
  • Server Load: High-frequency non-blocking requests can overload your server. Monitor your server's performance.
  • Security Concerns: Properly validate and sanitize inputs to mitigate potential security threats.

Summary Table

MethodDescriptionKey Configurations
fsockopenMinimal PHP built-in functionUse non-blocking stream options Close stream immediately after sending data
curl with OptionsVersatile, robust HTTP clientSet CURLOPT_RETURNTRANSFER to false Limit CURLOPT_TIMEOUT_MS
exec with curlShell execution of HTTP requestsUse & to send process to background Redirect output to /dev/null

By adopting the techniques above, you can efficiently make HTTP requests without waiting for responses in PHP, significantly enhancing the performance of your applications where appropriate.


Course illustration
Course illustration