Determine in php script if connected to internet?

前端 未结 11 1042
轮回少年
轮回少年 2020-11-30 21:28

How can I check if I\'m connected to the internet from my PHP script which is running on my dev machine?

I run the script to download a set of files (which may or ma

11条回答
  •  青春惊慌失措
    2020-11-30 21:56

    Just check the result of wget. A status code of 4 indicates a network problem, a status code of 8 indicates a server error (such as a 404). This only works if you call wget for each file in sequence, rather than once for all the files.

    You can also use libcurl with PHP, instead of calling wget. Something like:

    foreach (...) {
        $c = curl_init($url);
        $f = fopen($filepath, "w")
        curl_setopt($c, CURLOPT_FILE, $f);
        curl_setopt($c, CURLOPT_HEADER, 0);
        if (curl_exec($c)) {
            if (curl_getinfo($c, CURLINFO_HTTP_CODE) == 200) {
                // success
            } else {
                // 404 or something, delete file
                unlink($filepath);
            }
        } else {
            // network error or server down
            break; // abort
        }
        curl_close($c);
    }
    

提交回复
热议问题