Get Google and Alexa rank of a domain using PHP

There are already a lot of ways to find gpr/alexa rank of a domain using php. But not all of them work on 64bit servers. Here is the code that I always use for finding the google page rank and alexa rank of a website.

Get Google Page rank

function google_page_rank($url) { // URL or domain name
    if (strlen(trim($url))>0) {
        $_url = eregi("http://",$url)? $url:"http://".$url;
        $pagerank = trim(GooglePageRank($_url));
        if (empty($pagerank)) $pagerank = 0;
        return (int)($pagerank);
    }
    return 0;
}

function GooglePageRank($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);
            }
        }
        fclose($fp);
        return $pagerank;
    }
}

function StrToNum($Str, $Check, $Magic) {
    $Int32Unit = 4294967296; // 2^32
    $length = strlen($Str);
    for ($i = 0; $i < $length; $i++) {
        $Check *= $Magic;
        if ($Check >= $Int32Unit) {
            $Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
            $Check = ($Check < -2147483648)? ($Check + $Int32Unit) : $Check;
        }
        $Check += ord($Str{$i});
    }
    return $Check;
}

function HashURL($String) {
    $Check1 = StrToNum($String, 0x1505, 0x21);
    $Check2 = StrToNum($String, 0, 0x1003F);
    $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)) << 2 ) | ($Check2 & 0xF0F );
    $T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
    return ($T1 | $T2);
}

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;
}

Find Alexa Rank

function alexaRank($domain){
    $remote_url = 'http://data.alexa.com/data?cli=10&dat=snbamz&url='.trim($domain);
    $search_for = '<POPULARITY URL';
    if ($handle = @fopen($remote_url, "r")) {
        while (!feof($handle)) {
            $part .= fread($handle, 100);
            $pos = strpos($part, $search_for);
            if ($pos === false)
            continue;
            else
            break;
        }
        $part .= fread($handle, 100);
        fclose($handle);
    }
    $str = explode($search_for, $part);
    $str = array_shift(explode('"/>', $str[1]));
    $str = explode('TEXT="', $str);

    return $str[1];
}

Hope this will help you. If you know any better(working) solution please let me know via comments.

Related posts:

  1. Most expensive domain names

19 Comments to “Get Google and Alexa rank of a domain using PHP”

  1. zp bappi 27 June 2009 at 12:42 pm #

    this is really amazing. the google page rank looks fine. but, i have a question about alexa ranking. wont it break when alexa changes its page (UI) layout? also, is it legal to get it this way?

    let me know if i can use it in my projects. thanks again for the great code. you rock!

  2. adnan 27 June 2009 at 12:58 pm #

    Bappi,

    Yes you are right. This is not the proper way for finding the alexa rank and it won’t work if alexa.com changes their layout. You can get it in formal way from this XML:

    http://data.alexa.com/data?cli=10&dat=snbamz&url=abcoder.com

    and the php code for this is:

    function alexaRank($domain){
        $remote_url = 'http://data.alexa.com/data?cli=10&dat=snbamz&url='.trim($domain);
        $search_for = '<POPULARITY URL';
        if ($handle = @fopen($remote_url, "r")) {
            while (!feof($handle)) {
                $part .= fread($handle, 100);
                $pos = strpos($part, $search_for);
                if ($pos === false)
                continue;
                else
                break;
            }
            $part .= fread($handle, 100);
            fclose($handle);
        }
        $str = explode($search_for, $part);
        $str = array_shift(explode('"/>', $str[1]));
        $str = explode('TEXT="', $str);
    
        return $str[1];
    }

    But the big problem with this is you won’t get correct alexa rank of subdomains from this. Say blogspot.com and abcoder.blogsopt.com will show same alexa rank, which is wrong.
    For this problem I’m using the method of parsing the alexa website and for now it’s getting accurate alexa rank for subdomains :)

    Lemme know if you get any better thing.

    Thanks

  3. adnan 27 June 2009 at 2:17 pm #

    Bappi,

    I guess http://data.alexa.com/data?cli=10&dat=snbamz&url=http://girlwithaonetrackmind.blogspot.com/ is providing the correct alexa rank of subdomain now!

    It seems they have updated their service. :)

  4. zp bappi 29 June 2009 at 12:02 pm #

    adnan,

    right you are! the above url is returning correct alexa rank for subdomains too. please modify your php and post it in comments to reflect the changes. that would be really helpful for me and others too.

    thanks again for your effort. :)

  5. zp bappi 29 June 2009 at 12:06 pm #

    oppss.. sorry. i did not notice that your previous code (in comment) is appropriate for this purpose. :P

  6. adnan 29 June 2009 at 12:17 pm #

    Bappi,

    Thank you. I’ve already posted the modified code in the comment, I’ll modify my post also..

    The interesting thing is last time I checked this code on 6 June here http://www.abcoder.com/alexa.php to find out the alexa rank of http://sethgodin.typepad.com and it returned 215 (the alexa rank of typepad.com). Now the same code is providing the correct alexa rank 8935 :)

  7. adnan 29 June 2009 at 2:48 pm #

    The alexa rank finding code in the main post is updated.

  8. Adnan 12 July 2009 at 6:54 am #

    usually developers dont use fopen for remote url and hosting servers also may not enable them due to security reason. Why dont you use fsockopen or cURL ?

  9. adnan 12 July 2009 at 10:24 am #

    @Adnan, good point, CURL is not enabled/supported by all hosting providers. I wrote the code for a module which is publicly used on various hosting providers.

    But thanks for your suggesting and I’ll update my code soon to use CURL if available otherwise fopen/fsockopen.

    Thanks

  10. Testmuku 18 August 2009 at 9:19 am #

    Thanks for this script

  11. Zyva 26 January 2010 at 5:32 pm #

    The Alexa script works perfectly, thanks a lot ;)

  12. adnan 26 January 2010 at 5:48 pm #

    @Zyva, glad to know that :)

  13. Daniel 26 March 2010 at 4:20 am #

    Hello how can i get popularity number from this code?
    http://data.alexa.com/data?cli=10&dat=snbamz&url=abcoder.com
    Could you post all code what I should insert in templates to display only this number?
    Thanks Daniel

  14. adnan 26 March 2010 at 8:17 am #

    @Daniel, If you open that url in browser you’ll see

    <POPULARITY URL="abcoder.com/" TEXT="338168"/>

    at bottom section. the value of TEXT is the alexa rank.

  15. Daniel 26 March 2010 at 9:32 pm #

    @adnan – Thanks for your respond , I knew where is the number in XML , but i wanted the code which retrieves only this number from this XML to display it in my template – just did it thanks to one good programmer, http://worldwidedancers.com/topsites/ , in first column I have Alexa list ,

    About Page rank , can you tell me pls. what code I need to add in templates to insert it in the column on the left next to the Alexa ?
    Thanks for your respond, Daniel

  16. jack 21 April 2010 at 9:53 pm #

    Thanks, it works great!
    It’s very useful!

    Thanks a lot for sharing

  17. AmilaDG 18 May 2010 at 2:04 pm #

    Thank you for the genius note. It’s work.

  18. JkrzSeven 24 June 2010 at 5:32 pm #

    Hi,

    Thanks for the script. But I have a little question about running it in a wordpress blog.
    My Blog is a listing of popular websites ordered by their Alexa Rank. Every post of my wordpress blog treats about a website.
    How Do I pick up a rank of a website and associate it with an article ID? May I use custom fields for doing that?

    Thanks for your help!

  19. ABM Adnan 24 June 2010 at 8:08 pm #

    @JkrzSeven, You may do this:

    1. In your post add a custom field, say “gpr” with the domain name of the site as value.

    2. In your template put an image with src=”gpr.php?domain=domain_name_of_the_site

    3. Make 10 different images like gpr_1.jpg to gpr_10.jpg and keep them in your images folder.

    4. In gpr.php calculate the gpr using my script and output an image like gpr_(page rank value).jpg


Leave a Reply