Quickly retrieving HTTP response status code of URL using HEAD method in PHP

Sunday, July 4, 2010 14:35
Posted in category PHP

Here is simple to retrieve the HTTP response status code of URL using HEAD method in PHP.

<?php

$parseurl = parse_url($_GET["url"]);

$service_port = getservbyname('www', 'tcp');

$address = gethostbyname($parseurl["host"]);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}

$result = socket_connect($socket, $address, $service_port);
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}

$in = "HEAD " . $parseurl["path"] . " HTTP/1.1\r\n";
$in .= "Host: " . $parseurl["host"] . "\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

socket_write($socket, $in, strlen($in));

if ($out = socket_read($socket, 2048)) {
    $response = explode("\n", $out);
    $response_status = explode(" ", $response[0]);
    $response_string = $response_status[1] . " " . $response_status[2];
    echo $response_string; // prints response code and status
}

socket_close($socket);
?>

The above php code, parse the querystring complete url, makes socket connection, pass the head method in headers and finally prints the response code and status.

Here is the example how to pass the complete url to above php code.

http.php?url=http://www.google.com/
You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply

*