Determine in php script if connected to internet?

Steve picture Steve · Feb 1, 2011 · Viewed 62.3k times · Source

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 may not exist) using wget. If I try the download without being connected, wget proceeds to the next one thinking the file is not present.

Answer

Alfred picture Alfred · Feb 1, 2011
<?php
function is_connected()
{
    $connected = @fsockopen("www.example.com", 80); 
                                        //website, port  (try 80 or 443)
    if ($connected){
        $is_conn = true; //action when connected
        fclose($connected);
    }else{
        $is_conn = false; //action in connection failure
    }
    return $is_conn;

}
?>