Home  >  Article  >  Backend Development  >  How to deal with PHP interface timeout

How to deal with PHP interface timeout

(*-*)浩
(*-*)浩Original
2019-09-25 11:15:363656browse

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();

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!

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
Previous article:what is php interfaceNext article:what is php interface