Google PageRank Component

By Chad R Smith (chadsmith729)
Google Page Ranking is being used less and less, but it's still out there and offered by accessing google's servers. When talking about Search Engine Optimization the main items to look at are Trust and Authority, however Google/Yahoo/Bing are not releasing the ability to get that information yet. Page Rank will just have to do for the time being.
This component will access google.com and and find the Google PageRank for any given URL. You could also add other domains to the $googleDomains variable, but doing so adds to the response time.

/app/controllers/components/googlepagerank.php

Component Class:

Download code <?php 
class GooglepagerankComponent {
    
//Public vars
    
var $googleDomains = Array("www.google.com");
        
// You can add more google owned domains here to check, but it increases the time to execute.
    
    
var $debugResult = Array();
    var 
$userAgent "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021204";
    var 
$cacheDir "/tmp";
    var 
$maxCacheAge 86400// = 24h (yes, in seconds)
    
var $useCache false;
    var 
$debug false;

    
//Private vars
    
var $PageRank = -1;
    var 
$cacheExpired false;


    function 
GetPR($url,$forceNoCache false) {
        
$total_exec_start $this->microtimeFloat();
        
$result=array("",-1);

        if ((
$url.""!="")&&($url.""!="http://")) {

            
$this->debugRes("url"$url);

            
$this->cacheDir .= (substr($this->cacheDir,-1) != "/")? "/":"";

            
// check for protocol
            
$url_ = ((substr(strtolower($url),0,7)!="http://")? "http://".$url:$url);
            
$host $this->googleDomains[mt_rand(0,count($this->googleDomains)-1)];
            
$target "/search";
            
$querystring sprintf("client=navclient-auto&ch=%s&features=Rank&q=%s",
                
$this->CheckHash($this->HashURL($url_)),urlencode("info:".$url_));
            
$contents="";

            
$this->debugRes("host"$host);
            
$this->debugRes("query_string"$querystring);
            
$this->debugRes("user_agent"$this->userAgent);

            
$query_exec_start $this->microtimeFloat();

            if (
$forceNoCache == true) {
                
$this->debugRes("force_no_cache""true");
            } elseif (
$contents $this->readCacheResult($url)) {
                
$this->debugRes("read_from_cache""true");
            } else {
                
$this->cacheExpired true;
            }


            
// let's get ranking
            
if (strlen(trim($contents)) == 0)
            if (@
function_exists("curl_init")) {

                
// allways use curl if available for performance issues
                
$ch curl_init();
                
curl_setopt($chCURLOPT_URL"http://".$host.$target."?".$querystring);
                
curl_setopt($chCURLOPT_RETURNTRANSFER1);
                
curl_setopt($chCURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_0);
                
curl_setopt($chCURLOPT_USERAGENT$this->userAgent);
                if (!(
$contents trim(@curl_exec($ch)))) {
                    
$this->debugRes("error","curl_exec failed");
                }
                
curl_close ($ch);
                
$this->debugRes("method""curl");

            } else {
                
$this->debugRes("error","curl not installed, trying to use fsockopen");
                
// use fsockopen as secondary method, to submit user agent
                
if ($socket  = @fsockopen($host"80"$errno$errstr30)) {

                    
$request  "GET $target?$querystring HTTP/1.0\r\n";
                    
$request .= "Host: $host\r\n";
                    
$request .= "User-Agent: ".$this->userAgent."\r\n";
                    
$request .= "Accept-Language: en-us, en;q=0.50\r\n";
                    
$request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
                    
$request .= "Accept: text/xml,application/xml,application/xhtml+xml,";
                    
$request .= "text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,";
                    
$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
                    
$request .= "Connection: close\r\n";
                    
$request .= "Cache-Control: max-age=0\r\n\r\n";

                    
stream_set_timeout $socket,10);
                    
fwrite$socket$request );
                    
$ret '';
                    while (!
feof($socket)) {
                        
$ret .= fread($socket,4096);
                    }
                    
fclose($socket);
                    
$contents trim(substr($ret,strpos($ret,"\r\n\r\n") + 4));
                    
$this->debugRes("method""fsockopen");
                } else {
                    
$this->debugRes("error","fsockopen failed, trying file_get_contents");
                    
// this way could cause problems because the Browser Useragent is not set...
                    
if ($contents trim(@file_get_contents("http://".$host.$target."?".$querystring))) {
                        
$this->debugRes("method""file_get_contents");
                    } else {
                        
$this->debugRes("error","file_get_contents failed");
                    }
                }

            }

            if (
$this->cacheExpired == true)
            
$this->updateCacheResult($url,$contents);

            
$this->debugRes("query_exec_time",$this->microtimeFloat() - $query_exec_start);

            
$result[0]=$contents;
            
// Rank_1:1:0 = 0
            // Rank_1:1:5 = 5
            // Rank_1:1:9 = 9
            // Rank_1:2:10 = 10 etc
            
$p=explode(":",$contents);
            if (isset(
$p[2])) $result[1]=$p[2];
        }

        if(
$result[1] == -1$result[1] = 0;
        
$this->PageRank =(int)$result[1];
        
$this->debugRes("total_exec_time"$this->microtimeFloat() - $total_exec_start);
        
$this->debugRes("result"$result);
        return 
$this->PageRank;

    }


    function 
debugRes($what,$sowhat) {
        if(
$this->debug == true) {
            
$debugbt debug_backtrace();
            
$what trim($what);
            
$sowhat trim($sowhat) . " (Line : ".$debugbt[0]["line"].")";
            if (
$what == "error") {
                
$this->debugResult[$what][] = $sowhat;
            } else {
                
$this->debugResult[$what] = $sowhat;
            }
        }
    }

    function 
microtimeFloat() {
        list(
$usec$sec) = explode(" "microtime());
        return ((float)
$usec + (float)$sec);
    }


    function 
readCacheResult($url) {
        if (
$this->useCache != true) {
            return 
false;
        }

        if (!
is_dir($this->cacheDir)) {
            
$this->debugRes("error","please create {$this->cacheDir}");
            return 
false;
        }

        
$urlp parse_url($url);
        
$host_ explode(".",$urlp["host"]);
        
$path_ = (strlen($urlp["query"])>0)? urlencode($urlp["path"].$urlp["query"]):"default";

        
$cache_file $this->cacheDir;

        for (
$i count($host_)-1;$i>=0;$i--) {
            
$cache_file .= $host_[$i]."/";
        }

        
$cache_file .= $path_;
        
$this->debugRes("cache_file"$cache_file);
        if (
file_exists($cache_file)) {
            
$mtime filemtime($cache_file);
            if (
time() - $mtime $this->maxCacheAge) {
                
$this->debugRes("cache""expired");
                
$this->cacheExpired true;
                return 
false;
            } else {
                
$this->cacheExpired false;
                
$this->debugRes("cache_age"time() - $mtime);
                return 
file_get_contents($cache_file);
            }
        }
        
$this->debugRes("error","cache file not exists (reading)");
        return 
false;
    }

    function 
updateCacheResult($url,$content) {
        if (
$this->useCache != true) {
            return 
false;
        }

        if (!
is_dir($this->cacheDir)) {
            
$this->debugRes("error","please create {$this->cacheDir}");
            return 
false;
        }

        
$urlp parse_url($url);
        
$host_ explode(".",$urlp["host"]);
        
$path_ = (strlen($urlp["query"])>0)? urlencode($urlp["path"].$urlp["query"]):"default";

        
$cache_file $this->cacheDir;
        for (
$i count($host_)-1;$i>=0;$i--) {
            
$cache_file .= $host_[$i]."/";
        }

        
$cache_file .= $path_;

        if (!
file_exists($cache_file)) {
            
$this->debugRes("error","cache file not exists (writing)");
            
$cache_file_tmp substr($cache_file,strlen($this->cacheDir));
            
$cache_file_tmp explode("/",$cache_file_tmp);
            
$cache_dir_ $this->cacheDir;
            for (
$i 0;$i<count($cache_file_tmp)-1;$i++) {
                
$cache_dir_ .= $cache_file_tmp[$i]."/";
                if (!
file_exists($cache_dir_)) {
                    if (!@
mkdir($cache_dir_,0777)) {
                        
$this->debugRes("error","unable to create cache dir: $cache_dir_");
                        
//break;
                    
}
                }
            }
            if (!@
touch($cache_file)) $this->debugRes("error","unable to create cache file");
            if (!@
chmod($cache_file,0777)) $this->debugRes("error","unable to chmod cache file");
        }

        if (
is_writable($cache_file)) {
            if (!
$handle fopen($cache_file'w')) {
                
$this->debugRes("error""unable to open $cache_file");
                return 
false;
            }
            if (
fwrite($handle$content) === FALSE) {
                
$this->debugRes("error""unable to write to $cache_file");
                return 
false;
            }
            
fclose($handle);
            
$this->debugRes("cached"date("Y-m-d H:i:s"));
            return 
true;
        }
        
$this->debugRes("error""$cache_file is not writable");
        return 
false;

    }

    
//convert a string to a 32-bit integer
    
function StrToNum($Str$Check$Magic) {
        
$Int32Unit 4294967296;  // 2^32
        
$length strlen($Str);
        for (
$i 0$i $length$i++) {
            
$Check *= $Magic;     
            
//If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), 
            //  the result of converting to integer is undefined
            //  refer to http://www.php.net/manual/en/language.types.integer.php
            
if ($Check >= $Int32Unit) {
                
$Check = ($Check $Int32Unit * (int) ($Check $Int32Unit));
                
//if the check less than -2^31
                
$Check = ($Check < -2147483648) ? ($Check $Int32Unit) : $Check;
            }
            
$Check += ord($Str{$i}); 
        }
        return 
$Check;
    }

    
//genearate a hash for a url
    
function HashURL($String) {
        
$Check1 $this->StrToNum($String0x15050x21);
        
$Check2 $this->StrToNum($String00x1003F);
        
$Check1 >>= 2;     
        
$Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 0x3F);
        
$Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 0x3FF);
        
$Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 0x3FFF);    
        
        
$T1 = (((($Check1 0x3C0) << 4) | ($Check1 0x3C)) <<) | ($Check2 0xF0F );
        
$T2 = (((($Check1 0xFFFFC000) << 4) | ($Check1 0x3C00)) << 0xA) | ($Check2 0xF0F0000 );
        
        return (
$T1 $T2);
    }
    
    
//genearate a checksum for the hash string
    
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 (
=== ($Flag 2)) {              
                
$Re += $Re;     
                
$Re = (int)($Re 10) + ($Re 10);
            }
            
$CheckByte += $Re;
            
$Flag ++;    
        }
    
        
$CheckByte %= 10;
        if (
!== $CheckByte) {
            
$CheckByte 10 $CheckByte;
            if (
=== ($Flag 2) ) {
                if (
=== ($CheckByte 2)) {
                    
$CheckByte += 9;
                }
                
$CheckByte >>= 1;
            }
        }
        return 
'7'.$CheckByte.$HashStr;
    }
}
?>

Now we have the component set up and working. Let's access and run a test.

Controller - /app/controllers/googlepageranks_controller.php

Controller Class:

Download code <?php 
class GooglepageranksController extends AppController {
    var 
$name 'Googlepageranks';
    var 
$components = array('Googlepagerank');
    
    
/*-----------------------------------------------------------
        Google Page Rank
    -------------------------------------------------------------*/
    
function googlepr($theURL){
        
$this->autoRender false;
        
$this->autoLayout false;
        
// Send to google.com and get the PageRank
        
echo $this->Googlepagerank->GetPR($theURL);
    }
}
?>

Open a web browser and go to http://{domain}/googlepageranks/googlepr/http%3a%2f%2fintegrascan.com
The output should say something like: 4

This is also available as a free API courtesy of The Easy API http://theeasyapi.com.

Happy Baking,
Chad

 

Comments 1424

CakePHP Team Comments Author Comments
 

Comment

1 Nice..

Thanks for the code, i always believed Google PR was something that wasn't directly accessible and had to be somehow 'stolen' indirectly from the Google toolbar.
Will check it and see if it works(i'm sure it does though).
Regards,
seo articles
Posted Apr 12, 2010 by Kevin Nash
 

Comment

2 Pr effects...

I think PR will always be around but all it really shows is how often a page gets spidered. My potty training site was PR2 and now after the update it has gone to a PR4.
Posted Apr 13, 2010 by Jill Bradlie
 

Comment

3 great post

Nice read on the famous google PR, but i though the where going to do away with that in their algorithm. I use to think this was the most important factor with googles index which intern would allow me to make money, but i see page rank is meaningless!
Posted Apr 18, 2010 by zadoc
 

Comment

4 good one

Its really an informative write up by Chad. Its a truth that the Google page ranking is not used much now a days. But it is still out there. While we think about the search engines , the trust and authority plays an important role. But still not much clarity is obtained in this area. Page rank will just have to do for time being. I have downloaded the code just for my information. I followed the procedure after downloading the code and got the output as you said. But page rank is not permanent and keeps on changing . Call Center Software .
Posted Apr 20, 2010 by brown
 

Comment

5 Google page rank

To be honest i have always tried my best to get the higher page rank for all my websites, by God's grace I have been successful enough in achieving the high rankings. Will continue to do my efforts in the future as well.
Freestyle Medela Web hosting
Posted Apr 22, 2010 by nicole hogan
 

Comment

6 PR Importance

Google PR's will be always around as long as users give the value ot it.
Personally it matters to me. Chad what you mean trust and authority, explain?. cheers NYC limousine service
Posted May 1, 2010 by Victor Bertrand
 

Comment

7 Page Rank

This is a great article about page rank. I really do not get caught up in pr but it is a real show of a site Kathy Purses.
Posted Jul 12, 2010 by John
 

Comment

8 Google PR

Heilerschule say great PHP Code, many Thanks for sharing
Posted Jul 12, 2010 by marcel
 

Comment

9 Re:Google PageRank Component

I am really interested in this program but I do not know much about it. After reading your article, i have more experiences to work with it. Your post is interesting and picturesque. I hope i can get your post in next time. Keep on!
prom dresses cheap prom dresses
Posted Jul 13, 2010 by prom dresses
 

Comment

10 Google Page Rank

I appreciate you for sharing this information. Nice read about Google Page Rank. Neus Gator
Posted Jul 14, 2010 by Neus Gator
 

Comment

11 thanks

This is a great article about page rank. I really do not get caught up in pr but it is a real show of a site.. identity theft protection
Posted Jul 14, 2010 by Jim
 

Comment

12 nice

I really do not get caught up in pr but it is a real show of a site.

Designer Resources, Php Tutorial
Posted Jul 15, 2010 by allby sie
 

Comment

13 hey

PR seems to ahve lost most of it's shine but it's still a metric that people put a lot of faith in for some reason. I think the underlying factors influencing PR are still very valid, but the PR number itself is pretty meaningless imho.

Purchase Insurance Dallas Mortgage Refinance
Posted Jul 15, 2010 by jim jones
 

Comment

14 thank you very much!

I really do not get caught up in pr but it is a real show of a site.
Louis Vuitton Outlet|
Discount Louis Vuitton|
Cheap Louis Vuitton Handbags
Posted Jul 16, 2010 by billylu
 

Comment

15 Nice one

I really not able to understand why my PR not up,However i can see improvement in alexa !
regards,
Sarkari naukri
Posted Jul 16, 2010 by Boby
 

Comment

16 thanks

This is a good article, and have a high page rank. this is great PHP Code, thanks for sharing.

To disk partition, I always use free partition manager!
Posted Jul 16, 2010 by jackam
 

Comment

17 Excellent Component

This is an excellent component. I was able to implement it and I'm grateful for the shortcut as I did not want to, nor am I sure I could have, done it myself. Caretaker Pool Systems - Social Bookmarks Eintragen
Posted Jul 16, 2010 by Anya Jordan
 

Comment

18 cool

What results are you getting with your implementation?

Porno izle
Posted Jul 17, 2010 by ahmet
 

Comment

19 PR

I agree PR is becoming less and less important. Google says that this is just one of the many factors to determine authority. I think they are just saying that because they want to stop the online high PR text link brokerage. But who knows

Youtube to MP3 converter,Youtube to Mp3,Convert Youtube to Mp3
Posted Jul 17, 2010 by Mike Thomas
 

Comment

20 you're probably right

I agree PR is becoming less and less important. Google says that this is just one of the many factors to determine authority. I think they are just saying that because they want to stop the online high PR text link brokerage. But who knows
You're probably right.. BUT.. I don't really see it slowing down.. it's the one thing that people can visibly take note of.. so, it is what it is I guess. PR 'seems' to make a difference for me.. but maybe it's just in my head. who knows..
Bathroom Vanities, work at home jobs
Posted Jul 17, 2010 by Lilly Branch
 

Comment

21 Google pagerank component

This is true Google PR now becoming less important and dependent on how many link back you have from high PR sites !
So it may be dependent on back link from others to you. But some of SEO experts talk a lot of about it.
Golf in Mallorca
Posted Jul 18, 2010 by Pramod
 

Comment

22 well..

well.. I'm pretty sure most people understand that by now.. that's what gives you PR after all anyway. So.. yeah.. that's pretty much confirmed I think. That's how I promote my Eismaschine & dog diets sites successfully.
Posted Jul 19, 2010 by lizaforst
 

Comment

23 thank you

Thank you very nice code.
Diziizle- ezel izle gonulcelen Canli dizi izleme sitesi. youtube izle, youtube giris Youtube Watch, download- Youtube izle, indir Diziizle dizisi Canli dizi izleme sitesi. Bedava flash oyunlar Free flash games - flash oyunlar
Posted Jul 20, 2010 by mark
 

Comment

24 Thank you

Thank you very nice code.
Diziizle- ezel izle gonulcelen Canli dizi izleme sitesi. youtube izle, youtube giris Youtube Watch, download- Youtube izle, indir Diziizle dizisi Canli dizi izleme sitesi. Bedava flash oyunlar Free flash games - flash oyunlar
Posted Jul 21, 2010 by mark
 

Comment

25 ed

When the majority of people will see the realistic way to solve that over time that it starts to blend suddenly. auto transport Yes, the will be read again without any doubt.
Posted Jul 22, 2010 by dan kaylee
 

Comment

26 great tutorial

This is quite an impressive undertaking.. I appreciate your time and effort in this guide. I'm going to do my best to follow it to a T and not ask too many questions :) My expertise is more in folding knife & pocket knife - which doesn't help me here at all unfortunately for me
Cody, grout stain guy
Posted Jul 23, 2010 by Cody Demmer
 

Comment

27 amazing contribution

This is an amazing contribution.. really.. I'm going to get to work looking into this ASAP.. busy listening to some hot gothic tunes right now.
strony internetowe lodz
Posted Jul 23, 2010 by KellyPilla
 

Comment

28 Simply not true.

Google Page Ranking is being used less and less, but it's still out there and offered by accessing google's servers. When talking about Search Engine Optimization the main items to look at are Trust and Authority, however Google/Yahoo/Bing are not releasing the ability to get that information yet. Page Rank will just have to do for the time being.

This is not true at all.

Webmaster
Hand Sanitizer
Posted Jul 23, 2010 by ken kaniff
 

Comment

29 Google PR

It is constant fight with Google to get high page rank I rank my electrical site to the first page in
orange county electrician

I up and down. Any one know how to stay on the top page!
Posted Jul 23, 2010 by Zoltan
 

Comment

30 Thank you

Google Pagerank, Alexa Popularity, Google Backlinks, (Both with and without API), Alexa Backlinks, Alexa Reach Rank, Yahoo Inbound Links, (Both with and without API), Number of Altavista Links, Number of All the Web Links, Number of Google Indexed Pages, Number of Yahoo Indexed Pages, Number of MSN Indexed Pages, Whether Listed in DMOZ Directory, Bing Indexed Pages, ASK indexed pages and also age of your domain.
3d Poker
Posted Jul 25, 2010 by William
 

Comment

31 PR

It seems PR have lost most of it's shine but it's still a metric that people put a lot of faith in for some reason. And I think the underlying factors influencing PR are still very valid .
SEO
Posted Jul 25, 2010 by Jack Kalus
 

Comment

32 Thanks and

Posted Jul 29, 2010 by spider
 

Comment

33 help

I'm pretty sure most people understand that by now, so thanks for your article.
pronostic sport
Posted Jul 29, 2010 by Phil
 

Comment

34 How

How do I compile and implement this code into a toolbar?

Mike
Refrigerator Water Filter
Posted Jul 29, 2010 by Bryan Wilkins
 

Comment

35 Great Ideas

Hey everyone. Interesting idea for a blog. I have been checking out a lot of blogs for cheap nickelback tickets and forums for cheap dave matthews band ticketsrecently. Some are really informative some are entertaining and some are a real crack up. I've got to admit it, good job on this blog, I'll be sure to look in again real soon id i need cheap wicked tickets.

Posted Jul 30, 2010 by Kane
 

Comment

36 hello

That is some inspirational stuff.Hydraulic jacks Never knew that opinions could be this varied.Hydraulic jacks Thanks for all the enthusiasm to offer such helpful information here Hydraulic jack
Posted Jul 31, 2010 by jini