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

How to Make Asynchronous GET Requests in PHP?

Patricia Arquette
Release: 2024-12-02 19:50:11
Original
385 people have browsed it

How to Make Asynchronous GET Requests in PHP?

Asynchronous GET Request in PHP

Making an asynchronous GET request in PHP can be achieved in a few different ways. One straightforward method is to use the file_get_contents() function. To retrieve the content from an external script using file_get_contents(), simply specify the URL as the parameter. The result can be stored in a variable for further processing or echoing.

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

Another approach is to fire off the GET request without waiting for a response using the curl_post_async() function. This function opens a socket, sends the request, and immediately closes the socket, returning control of the script without blocking.

function curl_post_async($url, $params)
{
    // ... code to parse the URL and prepare the request ...
    $fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);

    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    // ... code to set up the request headers and body ...

    fwrite($fp, $out);
    fclose($fp);
}
Copy after login

By utilizing these techniques, you can make both synchronous and asynchronous GET requests in PHP, allowing you to send requests without blocking the script's execution.

The above is the detailed content of How to 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