Tag Archives: function

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.

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!

How to get currently logged on windows username in PHP and Javascript

It is very simple to get the current windows username in PHP. The following one line of code will output the username of the system where the server is running. If you are running this from localhost then your system login name will be shown. But you can not get the visitor’s system login username.

<?php echo getenv("username"); ?>

By using javascript (actually VBscript) you can get the visitor’s windows username. But there are also limitations. It only works on IE.

<script language="VBscript">
Dim X
set X = createobject("WSCRIPT.Network")
dim U
U=x.UserName
MsgBox "username: " & U
</script>
<script language="Javascript">
var a = U;
alert("Hello, " + a.toString());
</script>

This code will show you the current windows username. But won’t work if run from http://. Open the page from your computer with IE and it’ll work, otherwise not.

Actually it is not possible to get the windows username of your website visitors as it is a security issue. So don’t waste your time if you are trying to do that.

Simplify your query easily

It’s always boring and time consuming writing long INSERT/UPDATE query. Generally when you need to insert a form data with a large number of fields into a single table it does not make any good sense to write the full query manually. For example “INSERT into tbl set name = ‘$_POST[name]‘ , email = ‘$_POST[email]‘ , ….. may be 30 fields! So how can you minimize your effort?

I have written a very simple PHP function for this:

<?php
function genquery($table, $data, $mode = 'insert into', $condition = '', $raw = '') {
	$res = mysql_query("select * from $table limit 1");

	$field_arr = array();
	for($i=0; $i < mysql_num_fields($res); $i++) {
		$field_arr[] = mysql_field_name($res, $i);
	}
	mysql_free_result($res);

	$qstr = $mode." ".$table." set ";
	$arr = array();
	foreach($data as $k => $v) {
		if(!in_array($k, $field_arr)) continue;
		$arr[] = $k." = '".$v."'";
	}
	$qstr .= implode(', ', $arr);

	$qstr .= ' ' . $raw;

	if($mode == 'update' && $condition != ''){
		$qstr .= ' where ' . $condition;
	}
	return $qstr;
}
?>

You must follow a simple way for using this function. The name of the input fields in the form should be same as the fields in the table of your database. I assume your form will be submitted in POST format. In fact a form with many fields is always submitted in post method.

Here is how to use this function:

<?php
include("qfn.php");
if(isset($_POST['submit'])){  // if the form is submitted

$q = genquery("tableName", $_POST, "INSERT INTO", '', '');
mysql_query($q);
}
?>

For updating use:

$q = genquery("tableName", $_POST, "UPDATE", " id = '$_SESSION[id]' ", '');
// the 4th parameter is the condition for update. Use your own condition.

You can use more than one condition like:

$q = genquery("tableName", $_POST, "UPDATE", " id = '$_SESSION[id]' AND uid = '$_SESSION[uid]' ", '');

The 5th parameter is for raw values like

"entry_date = CURDATE(), status = '1' "

You can use the 5th parameter both for INSERT and UPDATE query. But the 4th parameter is only for UPDATE query.

Hope this will help you a lot and save your time & energy.

Download the php file in zip format.