Archive for June, 2009

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.

Calling a function randomly / arbitrarily

Say you have 2 or more functions in your actionscript, for some reason you have to call one of them arbitrary and dynamically. You don’t know which function will call at run time. You can do it by this way….

var myfunctions:Array = new Array();
myfunctions[0] = "myfunc1";
myfunctions[1] = "myfunc2";
myfunctions[2] = "myfunc3";

function  myfunc1 (){
   trace("This is my function number 1");
}
function  myfunc2 (){
   trace("This is my function number 2");
}
function  myfunc3 (){
   trace("This is my function number 3");
}

function randRange(min:Number, max:Number):Number {
   var randNum:Number = Math.round(Math.random()*(max-min))+min;
   return randNum;
}
btn.onPress = function(){
   var randomNumber = randRange(0,myfunctions.length-1);
   _root[myfunctions[randomNumber]]();
}

Google Voice coming shortly

Google voice
Google is starting a new service “Google Voice” within a few weeks. This amazing new voice service will give the users a single phone number and all the calls to their existing phones will be diverted to this single number. It’ll have voice mail feature and users can access this service using any mobile phone or internet (browser). The voice messages will be converted to text and thus it’ll be easily searchable, free sms service, forward voice mails directly to email addresses, recording incoming calls only and listen / download them later from web and many more. The interface will be similar to gmail.
google voice mail
Google will certainly integrate it with android and it’ll support other platforms too. For details visit voice.google.com

iPorn for iPhone!

iPorn for iPhone Apple has released the new iPhone 3G S. It’s 2x faster and has live streaming video support. This feature of new iPhone is gonna be “utilized” in a different way. iPorn is providing free hard core videos for iPhone users. And the most interesting thing is there is rumor that apple is involved in this for the marketing of iPhone. On iPorn site they say -
Just type “iPorn” in your iPhone browser and you’ll be directed to our iPhone-formatted site. Your mobile phone number is your password
The rumor sounds a little true ;)
The site is optimized and user friendly for iPhone and iPod touch with touch navigation, rotate screen, watch, post & share videos/photos, send private messages to other members even create your own profile page and more…s

SEO tips: Reduce your unwanted external links using jQuery

In SEO one of the most important factor is reducing the external links. A common practice is using rel=”nofollow” or rel=”external nofollow” or rel=”nofollow me” with <a> tag to reduce the page rank leakage. But do you know there may be some external links on your blog which you are not aware of at all! In most cases WordPress blogs have links to wordpress.org and the theme provider’s site at bottom which does not have the “nofollow” attribute. The indexing and ranking procedure of search engine is still a mystery and there are rumors that some spiders follow the nofolllow links! So adding a nofollow is not always the good solution. Some WP plugins and widget codes insert direct link to their sites.

It may sound odd.. the most popular social bookmarking widget AddThis button code has direct link to their site and we never bother to look inside their code. Here is the AddThis button code:

<!-- AddThis Button BEGIN -->
<div>
<script type="text/javascript">
	var addthis_pub="4a11abc75f3cd444";
</script>
<a href="http://www.addthis.com/bookmark.php?v=20"
onmouseover="return addthis_open(this, '', '[URL]', '[TITLE]')"
onmouseout="addthis_close()"
onclick="return addthis_sendto()">
<img src="http://s7.addthis.com/static/btn/sm-plus.gif" width="16" height="16" alt="Bookmark and Share" style="border:0"/>
</a>
<script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script>
</div><!-- AddThis Button END -->

You see there is a direct link to http://www.addthis.com/bookmark.php?v=20. If you remove this the code won’t work and adding nofollow is not a good solution. I modified their code in my own way and removed the link.
To do this first I saved the js (http://s7.addthis.com/js/200/addthis_widget.js) that is loaded at first from the addthis server. According to their TOS there is no problem if I cache their js code and use an image of my own choice. So I used a different addthis image with shadow which you can see at top-left side of this post and added a pseudo class “bkmrk” to it.

This is the php code for the template:

<img class="bkmrk" src="<?php bloginfo('template_url'); ?/>/images/addthis.gif" alt="bookmark" title="< ?php the_title(); ?>" name="< ?php the_permalink(); ?>" border="0" />

The title of the img tag is title of the post and the value of the name attribute is permalink.

Then I included the js and jQuery library and used this simple code on domready:

jQuery(function(){
    jQuery("img.bkmrk").each(function(){
        var url = jQuery(this).attr("name");
        var title = jQuery(this).attr("title");
        jQuery(this).wrap('<a onclick="return addthis_sendto()" onmouseout="addthis_close()" onmouseover="return addthis_open(this, \'\', \'' + url + '\', \'' + title + '\')" href="http://abcoder.com/"></a>');
    });

    jQuery("span#wp").replaceWith('<a rel="external nofollow" href="http://wordpress.org" title="WordPress" target="_blank">WordPress</a>');
    jQuery("span#theme").replaceWith('<a rel="external nofollow" href="http://web2themes.com" title="WordPress Themes" target="_blank">Web 2.0 Themes</a>');
});

This code simply adds the same functionality but the big difference is search bots won’t find the links as this is done using javascript. So if you see the html source code you won’t see any direct link to addthis.com. The last 2 lines of the code is for links to wordpress.org and web2themes.com.
Isn’t it smart?

However I’m not 100% sure if adapting this method is legal or not! So use this at your own risk. On some blogs I’ve noticed this method being used for links to the commentators website. But right now I’m not sure which wordpress plugin they use for this purpose.

jQuery cycle plugin as carousel

The jQuery cycle plugin is really amazing! I love this plugin for its huge options for image/div slide show. Right now I’m working on a project which has 3 slideshow on one page. One is simple fade effect with text divs, another one is also fade effect with div + image + text and play/pause, next/back option. The third one is a simple carousel with continuous play mode.

I implemented the first two easily with cycle plugin. But I got stuck with the carousel one. The play and the next state is fine as I used the “scrollLeft” fx. The problem is when I click previous button the fx should be “scrollRight” and not “scrollLeft”. I thought it may need a little complex customized function to do this job of applying different transition effect on previous and next event. I had no clue for it. Even no help from google search! I do not like using a lot of plugins at a time. I know there is jCarousel / jCarousel lite plugin for this, but I still believe there must be a way for doing this with cycle.

It took several hours to find out the simple solution. It’s already inside the cycle plugin, but kinda hidden! I am using the “scrollHorz” fx effect and it is fixed now. WOW! again I discovered that “cycle” is really a marvelous plugin of jQuery.

Here is the example on the malsup site: http://www.malsup.com/jquery/cycle/scrollhv.html

This is the simple code I used:

$('#carousels').cycle({
    prev: '#left-arrow',
    next: '#right-arrow',
    pause: 1,
    fx: 'scrollHorz',
    timeout: 6000
});

IE6 png alpha transparency fix for dynamically loaded images via ajax

IE6 is always a nightmare for web developers. The most painful drawback is it does not support the alpha transparency of transparent png images and you know how to solve this problem using iepngfix or jquery.pngFix.js.

You must be thinking.. what is new in my post then!! Have you ever used any of them for dynamic png images? Some people call it “Loading an image via ajax”. Let me explain what I mean by “dynamic png images”.. say you have a page where clicking on a link does not reload the page, but load a transparent/semitransparent png image. Most specifically, I was working on a project where user types some text in a text box, it is converted to transparent png image on the fly using php and then it is displayed inside a div which has a graph-paper like background-image. This whole thing is done without reloading the page at all.

It looks okay on FF, safari, IE7 but on IE6 the transparent portion looks Grey. The iepngfix.htc script didn’t help, cos it only works on the images which are loaded and showed at the beginning of page loading. After the page is fully loaded and you load another png image using ajax this script won’t work. But I could not do that for my project as it is meant to be loaded dynamically using ajax for the sake of advanced user experience.

I started googling for it, no luck. Finally I modified a portion of code used in the iepngfix.htc file and fixed the problem using this simple javascript code. (FYI, I was using YUI so only the browser checking part is done using it, you can use jQuery or pure javascript for browser detection)

var textImage = new Image();
textImage.src = "text.png"; // src of the png image. okay if not ie6
if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie < 7) { // if IE 5+ or 6 or 6+
    var timg_src = textImage.src;  // textImage
    var new_img = new Image();  // just as a preloader
    new_img.src = timg_src;

    new_img.onload = function(){ // remember, the image is being loaded dynamically, so apply the filter after it is loaded.
        var ti = document.getElementById("textImage"); // the ID of the img tag where it'll be loaded
        ti.style.width = new_img.width; // you can get the width/height of image after it is fully loaded
        ti.style.height = new_img.height; // and you must "DEFINE" the image height/width. "auto" height/width won't work!

        // This is it. apply the filter :)
        ti.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + timg_src + "', sizingMethod='scale')";
        ti.setAttribute('src', 'blank.gif'); // don't forget this part. the image src is replaced with a blank gif image.
    }
}

Here is another version of the code which is not for dynamic images. It’s alternative of iepngfix.htc. In some cases you may not like using iepngfix.htc, rather want to control it yourself. For example if your page has hundreds of png images which are not transparent and only a few images that are transparent, in this case using iepngfix.htc will make the whole process too slow. I applied a pseudo class “png” to all png images & divs with png background image with fixed height & width and applied this simple jQuery code:

$(window).load(function(){ // after all the images are loaded
    if ($.browser.msie && parseInt($.browser.version.substr(0, 1)) < 7) { // ie6 or 5
        $("img.png").each(function(){
            $(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + $(this).attr('src') + "', sizingMethod='scale')").attr("src", "images/blank.gif");
        });
        $("div.png").each(function(){
            var bg = $(this).css("backgroundImage");
            bg.match(/^url[("']+(.*\.png)[)"']+$/i);
            bg = RegExp.$1;
            $(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bg + "', sizingMethod='crop')").css("backgroundImage", "none");
        });
    }
});

Hope you’ll find it helpful. Please let me know if you have any better idea.

Using Dreamweaver Spry validation with jQuery ajax form plugin

Writing form validation code manually is a boring task. Not only that, editing or adding new fields each time and modifying the validation code accordingly is such a pain. When Dreamweaver added the Spry form validation with CS3 the nightmare is over. The greatest feature of using it is you can do the form validation work automatically with a couple of mouse clicks and no hand written code! And you can easily change/edit or add/remove the fields.

I know jQuery has simple validation plugin but you have to write the codes for it, which is time consuming. I always use the spry validation of dreamweaver as I learned using it for it’s simplicity. When I tried to use it with the jQuery ajax form submit plugin I got disappointed. It didn’t work! I didn’t stop trying. And finally I found the way which I’m gonna share with you :)

Here is the simple code that you need in the “beforeSubmit” parameter of $.ajaxForm

$("#formID").ajaxForm({
    url: "submit.php",
    beforeSubmit: function(formData, jqForm, options){
        if (Spry) { // checks if Spry is used in your page
            var r = Spry.Widget.Form.validate(jqForm[0]); // validates the form
            if (!r)
                return r;
        }
    },
    success: successFunction,
    complete: completeFunction
});

Hope that’ll help a lot boosting your web development.

Problem with resizing corrupted images using PHP image functions

As a programmer we must always think about the exceptional situations. Generally I use my own function to resize uploaded images. It supports jpg, gif, png images with transparency which is “almost” okay.

<?php
// example use
// resizeImage("corrupted_image_1.jpg", "corrupted_image_resized.jpg", 100, 100, "jpg");
function chkImgExt($n){
	$tmp = explode('.', $n);
	$ext = strtolower(array_pop($tmp));
	if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif' || $ext == 'png')
		return $ext;
	else
		return false;
}

function resizeImage($src, $dest, $w, $h, $ext){
	$real_path = dirname(__FILE__) . '/';
	$tmpFile = $real_path."tmp_images/".time().'TMP.'.$ext;
	copy($src, $tmpFile); // you may use move_uploaded_file() if the $src is a $_FILES referance
	@chmod($tmpFile, 0777);
	$src = $tmpFile;
	list($width, $height) = @getimagesize($src);
	$new_width = $w;
	$new_height = $h;

	switch($ext){
		case 'jpg':
			$image = imagecreatefromjpeg($src);
			break;
		case 'jpeg':
			$image = imagecreatefromjpeg($src);
			break;
		case 'gif':
			$image = imagecreatefromgif($src);
			break;
		case 'png':
			$image = imagecreatefrompng($src);
			break;
		} 	

	// Resample
	$image_p = @imagecreatetruecolor($new_width, $new_height);
	if ( ($ext == 'gif') || ($ext == 'png') ) {
		$trnprt_indx = imagecolortransparent($image);

		// If we have a specific transparent color
		if ($trnprt_indx >= 0) {

			// Get the original image's transparent color's RGB values
			$trnprt_color = imagecolorsforindex($image, $trnprt_indx);

			// Allocate the same color in the new image resource
			$trnprt_indx = imagecolorallocate($image_p, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);

			// Completely fill the background of the new image with allocated color.
			imagefill($image_p, 0, 0, $trnprt_indx);

			// Set the background color for new image to transparent
			imagecolortransparent($image_p, $trnprt_indx);
		}
		// Always make a transparent background color for PNGs that don't have one allocated already
		elseif ($ext == 'png'){
			// Turn off transparency blending (temporarily)
			imagealphablending($image_p, false);

			// Create a new transparent color for image
			$color = imagecolorallocatealpha($image_p, 0, 0, 0, 127);

			// Completely fill the background of the new image with allocated color.
			imagefill($image_p, 0, 0, $color);

			// Restore transparency blending
			imagesavealpha($image_p, true);
		}
	}

	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

	if(file_exists($dest)){
		@unlink($dest);
	}
	// Output
	switch($ext){
		case 'jpg':
			imagejpeg($image_p, $dest, 100);
			break;
		case 'jpeg':
			imagejpeg($image_p, $dest, 100);
			break;
		case 'gif':
			imagegif($image_p, $dest);
			break;
		case 'png':
			imagepng($image_p, $dest);
			break;
	}

	imagedestroy($image_p);
	unlink($tmpFile);
	return true;
}
?>

But when I tried resizing these 2 images (corrupted_image_1.jpg, corrupted_image_2.jpg) it failed! The error is:

gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 9 extraneous bytes before marker 0xd9

I don’t know what does it mean!

First I thought the problem may be due to large file size or GD. I tried with larger file and it worked fine! Then I opened the corrupted images with photoshop and just save as jpg again, and yes it worked. It does not make good sense to me. How a general user will do that? I searched a lot on Google and got a lot of alternative image resizing codes and none of them worked. :(

Now what? Yes I used phpThumb long ago and to me (also most of you) it feels like using a lot of unnecessary codes just for simply resizing a silly image! I can’t believe phpThumb created the thumbnails of both of the corrupted images! yes, using GD! no imagemagick.

I have no idea how phpThumb do it? I never dare to look inside their codes :P
Here is the code using phpThumb to resize the images:

<?php
	require_once('phpthumb/phpthumb.class.php');
	$phpThumb = new phpThumb();
	$capture_raw_data = false; 	$phpThumb->resetObject();
	$phpThumb->setSourceFilename($targetFile); // your source image file
	$output_filename = $tpath; // output file path
	$phpThumb->setParameter('w', 100); // thumbnail width
	$phpThumb->setParameter('q', 100); // thumbnail quality
	$phpThumb->setParameter('config_output_format', 'jpeg'); // preferred thumbnail format 

	if ($phpThumb->GenerateThumbnail()){
		if($phpThumb->RenderToFile($output_filename)){
			// success
		} else {
			$msg = "Error during resizing \n" . $phpThumb->fatalerror . '  ' . $phpThumb->debugmessages;
		}
	} else {
		$msg = "Error with file\n" . $phpThumb->fatalerror . '  ' . $phpThumb->debugmessages;
	}
?>

If you are using your own function for image resizing please check with these 2 files (corrupted_image_1.jpg, corrupted_image_2.jpg). If you see it doesn’t work I would suggest to use phpThumb, it’s free. You should also make sure your web host has the latest php version on the server or go with a php hosting provider, that specializes in it.

Thanks a lot to phpThumb for their amazing work!