Using php to ping a website

I want to create a php script that will check the domain and display the response time along with the total request size.

This will be used to monitor a network of websites. I tried it with curl, here is the code that I have so far:

function curlTest2($url) {
    clearstatcache();

    $return = '';

    if(substr($url,0,4)!="http") $url = "http://".$url;

    $userAgent = 
       'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

    $execute = curl_exec($ch);

    // Check if any error occured
    if(!curl_errno($ch)) {
        $bytes      = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        $return = 'Took ' . $total_time . ' / Bytes: '. $bytes;        
    } else {
        $return = 'Error reaching domain';
    }
    curl_close($ch);

    return $return;

}

And here fopen is used

function fopenTest($link) {

    if(substr($link,0,4)!="http"){ 
    $link = "http://".$link;
    }

    $timestart = microtime();

    $churl = @fopen($link,'r');

    $timeend = microtime();
    $diff = number_format(((substr($timeend,0,9)) + (substr($timeend,-10)) - 
        (substr($timestart,0,9)) - (substr($timestart,-10))),4);
    $diff = $diff*100;

    if (!$churl) {
        $message="Offline";
    }else{
        $message="Online. Time : ".$diff."ms ";
    }

    fclose($churl); 

    return  $message;

}

Is there a better way to ping a site using php?

+3
source share
7 answers

You can use xmlrpc ( xmlrpc_client ). Not sure which advantages / disadvantages are twisted.

Drupal uses xmlrpc for this purpose (look at the ping module).

0
source

, curl , , , :

$site = "google.com";
ob_start();
system("ping " . escapeshellarg($site));
print ob_end_flush();

, , -, . curl .

+5

exec() wget:

$response = `wget http://google.com -O -`;

.

suhosin, http (301, 302...) .

+2

Curl/Fopen, , file_get_contents , fopen.

+1

curl .

, useragent. , .

0

Perhaps this Net_Ping pear is what you are looking for. It is no longer supported, but works.

0
source

If remote fopen is enabled, file_get_contents()it will do the trick too.

0
source

Source: https://habr.com/ru/post/1713091/


All Articles