使用php ping一个网站 [英] Using php to ping a website

查看:229
本文介绍了使用php ping一个网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个php脚本,它将ping一个域并列出响应时间以及请求的总大小。

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

这将用于监控网站的网络。我尝试使用 curl ,这里是我到目前为止的代码:

This will be used for monitoring a network of websites. I tried it with curl, here is the code 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;

}

这里是一个使用fopen

And here is one using fopen

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;

}

有更好的方法使用php ping网站吗?

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

推荐答案

您可以使用xmlrpc( xmlrpc_client )。不知道curl的优点/缺点是什么。

You could use xmlrpc (xmlrpc_client). Not sure what the advantages/disadvantages to curl are.

Drupal使用xmlrpc实现这个目的(查看ping模块)。

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

这篇关于使用php ping一个网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆