Home > General > How to get Google page ranks with PHP.

How to get Google page ranks with PHP.

This snippet of PHP code will show you how to get a Google page rank for a specific website. The function below will return the page rank as an integer. The code was pulled from the wordpress links directory plugin located here.

<?php
function getpagerank($url){
        $fp = fsockopen("toolbarqueries.google.com", 80, $errno, $errstr, 30);
        if(!$fp){
                echo "$errstr ($errno)<br />\n";
        }else{
                $out="GET /search?client=navclient-auto&ch=".CheckHash(HashURL($url))."&features=Rank&q=info:".$url."&num=100&filter=0
 HTTP/1.1\r\n";
                $out.="Host: toolbarqueries.google.com\r\n";
                $out.="User-Agent: Mozilla/4.0 (compatible; GoogleToolbar 2.0.114-big; Windows XP 5.1)\r\n";
                $out.="Connection: Close\r\n\r\n";

                fwrite($fp, $out);

                while(!feof($fp)){
                        $data=fgets($fp, 128);
                        $pos=strpos($data, "Rank_");
                        if($pos===false){} else{
                                $pagerank = substr($data, $pos + 9);
                                return $pagerank;
                        }
                }
                fclose($fp);
        }
}

function CheckHash($Hashnum){
	$CheckByte=0;
	$Flag=0;

	$HashStr=sprintf('%u', $Hashnum);
	$length=strlen($HashStr);

	for($i=$length-1; $i>=0; $i--) {
		$Re=$HashStr{$i};
		if(1===($Flag % 2)){
			$Re+=$Re;
			$Re=(int)($Re/10)+($Re%10);
		}
		$CheckByte+=$Re;
		$Flag++;
	}

	$CheckByte %= 10;
	if (0 !== $CheckByte){
		$CheckByte=10-$CheckByte;
		if (1 === ($Flag % 2) ) {
			if (1 === ($CheckByte % 2)) {
				$CheckByte += 9;
			}
			$CheckByte >>= 1;
		}
	}
	return '7'.$CheckByte.$HashStr;
}

?>
Categories: General Tags: ,
Digg: DIGG ME
  1. xerxes
    August 13th, 2009 at 22:28 | #1

    Hi,

    I’m not sure what you mean by

    CheckHash(HashURL($url))

    These functions are custom ones?

  2. December 30th, 2009 at 11:47 | #2

    Xerxes, The CheckHash function was added.

  1. No trackbacks yet.