Home >Backend Development >PHP Tutorial >How Can PHP Make Asynchronous HTTP Requests Without Blocking?

How Can PHP Make Asynchronous HTTP Requests Without Blocking?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 22:01:14624browse

How Can PHP Make Asynchronous HTTP Requests Without Blocking?

Asynchronous HTTP Requests in PHP: How to Avoid Waiting for Responses

In PHP, handling HTTP requests typically involves using blocking functions like file_get_contents(), which pauses script execution until a response is received. This can limit efficiency, especially when making multiple or non-time-sensitive requests.

Solution: Non-Blocking HTTP Requests

To overcome this limitation, PHP offers methods for making non-blocking HTTP requests. One approach is to use stream_context_create():

$options = [
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/json',
        'content' => json_encode($data)
    ],
    'ssl' => [
        'verify_peer' => false
    ]
];
$context = stream_context_create($options);
file_get_contents("http://example.com/api", false, $context);

This initiates an HTTP request without waiting for a response. However, it's important to note that the verify_peer option is set to false to avoid certificate verification issues.

Custom Implementation with Sockets

Another option is to create sockets directly using PHP's fsockopen() function:

function post_without_wait($url, $params)
{
    // Prepare POST data and URL parameters
    $post_string = http_build_query($params);

    $url_parts = parse_url($url);
    $host = $url_parts['host'];
    $port = isset($url_parts['port']) ? $url_parts['port'] : 80;

    $socket = fsockopen($host, $port);

    // Construct HTTP POST request header
    $request = "POST {$url_parts['path']} HTTP/1.1\r\n";
    $request .= "Host: {$host}\r\n";
    $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $request .= "Content-Length: " . strlen($post_string) . "\r\n";
    $request .= "Connection: Close\r\n\r\n";
    $request .= $post_string;

    // Send HTTP request and close socket
    fwrite($socket, $request);
    fclose($socket);
}

This function sends an HTTP POST request without waiting for a response. It requires a URL and an array of parameters as arguments.

The above is the detailed content of How Can PHP Make Asynchronous HTTP Requests Without Blocking?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn