user1532948
user1532948

Reputation:

how to get the http headers of Server software and set the timeout

I'm trying to get the HTTP headers but just the server software example: Apache, Microsoft-iis,Nginx,etc

The function

get_headers($url,1); 

it is too slow i want to set time out if it is possible or an other way ??

thanks

Upvotes: 0

Views: 213

Answers (4)

Siren
Siren

Reputation: 446

Get the headers by curl or fsockopen, parse it that you want .

the function of fsockopen is last argument for a timeout.

the function of curl calls "curl_setopt($curl, CURLOPT_TIMEOUT, 5) " that for a timeout.

For example:

function getHttpHead($url) {
$url = parse_url($url);
if($fp = @fsockopen($url['host'],empty($url['port']) ? 80 : $url['port'],$error,
    $errstr,2)) {
    fputs($fp,"GET " . (empty($url['path']) ? '/' : $url['path']) . " HTTP/1.1\r\n");
    fputs($fp,"Host:$url[host]\r\n\r\n");
    $ret = '';
    while (!feof($fp)) {
        $tmp = fgets($fp);
        if(trim($tmp) == '') {
            break;
        }
        $ret .= $tmp;
    }
    preg_match('/[\r\n]Server\:\s([a-zA-Z]*)/is',$ret,$match);
    return $match[1];
    //return $ret;
} else {
    return null;
}
}
$servername= getHttpHead('http://google.com');

echo $servername;

Upvotes: 0

williamvicary
williamvicary

Reputation: 805

This would set the code to timeout after 2 seconds, you can use CURLOPT_TIMEOUT_MS if you want milliseconds.

$timeoutSecs = 2;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, true); // Return the header
curl_setopt($ch, CURLOPT_NOBODY, true); // Don't return the body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return to a variable instead of echoing
curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutSecs);

$header = curl_exec($ch);
curl_close($ch);

Edit: Note you won't just be able to get a single header from this, it will return the whole header (which won't be any slower than getting just one segment to be honest) so you will need to create a pattern to pull the "Server:" header.

Upvotes: 1

Matt S
Matt S

Reputation: 15374

For the local server, the $_SERVER variable will give you everything exposed by the web server in SERVER_* keys.

For remote servers you can use libcurl and request just the headers. Then parse the response. It can still be long delay depending on network connectivity and the speed of the other server. To avoid a long delay, e.g. for an offline server, set the curl option for a short timeout (e.g. 5 seconds) using curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5).

Upvotes: 1

Julio
Julio

Reputation: 2290

You can do this with cURL, which will allow you to get the response from remote servers. You can set a timeout with cURL as well.

Upvotes: 0

Related Questions