Home > Backend Development > PHP Tutorial > How Can I Make Asynchronous GET Requests in PHP?

How Can I Make Asynchronous GET Requests in PHP?

Linda Hamilton
Release: 2024-12-08 12:36:11
Original
387 people have browsed it

How Can I Make Asynchronous GET Requests in PHP?

Asynchronous GET Requests in PHP

Making asynchronous GET requests in PHP allows for efficient communication with external scripts without blocking the main thread.

Using file_get_contents()

For GET requests where the output is not required, file_get_contents() can be employed:

$output = file_get_contents('http://www.example.com/');
Copy after login

Asynchronous Requests with fsockopen()

To make asynchronous requests without waiting for a response, you can use fsockopen():

function make_async_get($url) {
    $parts = parse_url($url);
    $fp = fsockopen($parts['host'],
        isset($parts['port']) ? $parts['port'] : 80,
        $errno, $errstr, 30);
    
    $out = "GET ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    
    fwrite($fp, $out);
    fclose($fp);
}

make_async_get('http://www.externalsite.com/script1.php?variable=45');
Copy after login

In this example, the socket is opened, the GET request is sent, and the socket is immediately closed without reading the response.

Note: If you require the output of the GET request, consider using curl_post_async() as shown in the referenced solution.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template