How to deal with PHP interface timeout

(*-*)浩
Release: 2023-02-24 20:02:02
Original
3631 people have browsed it

Generally we access HTTP in many ways, mainly: curl, socket, file_get_contents() and other methods.

If the other party's server never responds, we will be in tragedy. It is easy to kill the entire server, so we also need to consider the timeout issue when accessing http.

How to deal with PHP interface timeout

[CURL access HTTP]

CURL is a relatively reliable lib library that we commonly use to access the HTTP protocol interface. , high performance, and some concurrency support functions. (Recommended learning: PHP programming from entry to proficiency)

Let us use the cURL extension to handle timeout control

If you want to handle it more accurately For timeout, use the cURL extension, which can set the connection timeout and read timeout (CURLOPT_TIMEOUTCURLOPT_CONNECTTIMEOUT).

If you want to control whether the HTTP interface must return at the millisecond level, you can also use the CURLOPT_TIMEOUT_MS and CURLOPT_CONNECTTIMEOUT_M constants.

Note that if you use these two constants, you must set curl_setopt($ch, CURLOPT_NOSIGNAL, 1);

The magic is here, the cURL expansion mechanism is very In particular, as much data as is obtained at the specified reading time is returned, and then the call is terminated, and the program does not report an error.

Look at the code:

function e_curl() {
    global $url;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    $response = curl_exec($ch);
    if ($response === false) {
        $info = curl_getinfo($ch);
        if ($info['http_code'] === 0) {
        return false;
        }
    }
    return true;}e_curl();
Copy after login

The above is the detailed content of How to deal with PHP interface timeout. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!