All about PHP/MySQL

Saturday, February 7, 2009

Remove Common Words from Search String

Before sending the user given search string to MySql, its a good idea to remove common words used in it so that it may not disturb any relevant results you have in your DB. Their are far more professional approaches out there for this task but here I am mentioning a very simple one.

Function:

function RemoveCommonWords($sText){
$CommonWords = array (
'at',
'the',
'and',
'of',
'in'
);
for ($x = 0; $x < count($CommonWords); $x++) {
$sText = str_replace(' ' . $CommonWords[$x] . ' ', ' ', $sText);
}
return $sText;
}

Usage:

$search_string = "sports shops in market";

$search_string = RemoveCommonWords($search_string);

Build your own list in the function against the variable $CommonWords.

Good Luck :)

PHP function for Basic Image Gallery

This PHP function is a very basic one, yet useful for a single page image gallery within a small website. It reads all the images from given folder and creates a simple looking gallery with given sized thumbnails.

Function:

function Create_Gallery($dir, $width, $height){

$folder=dir($dir);

$gallery_html = '<div> ';

while($folderEntry=$folder->read())
{
if ($folderEntry != "." && $folderEntry != ".."){
$gallery_html .= ' <a href="'.$dir.'/'.$folderEntry.'"> <img style="border: 6px double rgb(84, 85, 101);" src="'.$dir.'/'.$folderEntry.'" alt="The thumb" width="'.$width.'" height="'.$height.'"/></a>';
}
}

$gallery_html .= ' </div> ';
$folder->close();

echo $gallery_html;

return;
}

Usage:

Create_Gallery("gallery_images", "200", "140");

Where 'gallery_images' is the folder containing the images. 2nd and 3rd arguments of the function are the desired width and height of thumbnails.

Good Luck :)

Friday, February 6, 2009

Putting watermark on an Image

While working on a project, I found this useful class for achieving watermarking task easily. Here is the code.

Class:

class watermark
{
var $img;
function create_watermark( $main_img_obj, $watermark_img_obj, $alpha_level = 100 )
{
$alpha_level /= 100;
$main_img_obj_w = imagesx( $main_img_obj );
$main_img_obj_h = imagesy( $main_img_obj );
$watermark_img_obj_w = imagesx( $watermark_img_obj );
$watermark_img_obj_h = imagesy( $watermark_img_obj );
$main_img_obj_min_x=10;
$main_img_obj_max_x=10;
$main_img_obj_min_y=10;
$main_img_obj_max_y=10;
$return_img = imagecreatetruecolor( $main_img_obj_w, $main_img_obj_h );

for( $y = 0; $y < $main_img_obj_h; $y++ )
{
for( $x = 0; $x < $main_img_obj_w; $x++ )
{
$return_color = NULL;
$watermark_x = $x - $main_img_obj_min_x;
$watermark_y = $y - $main_img_obj_min_y;
$main_rgb = imagecolorsforindex( $main_img_obj,
imagecolorat( $main_img_obj, $x, $y ) );
if ($watermark_x >= 0 && $watermark_x < $watermark_img_obj_w && $watermark_y >= 0 && $watermark_y < $watermark_img_obj_h )
{
$watermark_rbg = imagecolorsforindex( $watermark_img_obj,
imagecolorat( $watermark_img_obj, $watermark_x, $watermark_y ) );
$watermark_alpha = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
$watermark_alpha = $watermark_alpha * $alpha_level;
$avg_red = $this->_get_ave_color( $main_rgb['red'],
$watermark_rbg['red'], $watermark_alpha );
$avg_green = $this->_get_ave_color( $main_rgb['green'],
$watermark_rbg['green'], $watermark_alpha );
$avg_blue = $this->_get_ave_color( $main_rgb['blue'],
$watermark_rbg['blue'], $watermark_alpha );
$return_color = $this->_get_image_color( $return_img, $avg_red, $avg_green, $avg_blue );
}
else
{
$return_color = imagecolorat( $main_img_obj, $x, $y );
}
imagesetpixel( $return_img, $x, $y, $return_color );
}
}
$this->img = $return_img;
}
function _get_ave_color( $color_a, $color_b, $alpha_level )
{
return round((($color_a*(1-$alpha_level))+($color_b*$alpha_level)));
}
function _get_image_color($im, $r, $g, $b)
{
$c=imagecolorexact($im, $r, $g, $b);
if ($c!=-1)
{
return $c;
}
$c=imagecolorallocate($im, $r, $g, $b);
if ($c!=-1)
{
return $c;
}
return imagecolorclosest($im, $r, $g, $b);
}
function write($target)
{
imagejpeg($this->img, $target, 100);
}
}

Usage:

$watermark = new watermark();
$main_img_obj = imagecreatefromjpeg("image.jpg"); //Image which you want to put watermark on
$watermark_img_obj = imagecreatefrompng("logo.png"); //Watermark image (PNG file)
$watermark->create_watermark( $main_img_obj, $watermark_img_obj, 100 );
$watermark->write("image_with_watermark.jpg"); //Output Image

It takes image.jpg, puts logo.png on it as watermark and saves it as a new image file named image_with_watermark.jpg. Thats it!

Happy Coding :)

Thursday, February 5, 2009

Calculating Age from Date of Birth

In some sections (e.g Profile pages) its nice to display the user's age for the page viewers. Its easier with the following function to calculate age by providing a valid date of birth.

Function:

function GetAge($DOB) {

list($Year, $Month, $Day) = explode("-",$DOB);
$YearDifference = date("Y") - $Year;
$MonthDifference = date("m") - $Month;
$DayDifference = date("d") - $Day;

if ($DayDifference < 0 || $MonthDifference < 0) {
$YearDifference--;
}

return $YearDifference;

}

Usage:

$age = GetAge("1981-05-18"); //Year-Month-Day

echo $age;

Happy Coding :)

Fetch a URL (with cURL)

cURL is a very useful PHP library which can be used to connect to different types of servers with different types of protocols. Here is a very basic example of its primary usage.

function fetchPage($url)
{

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$responce = curl_exec($ch);
curl_close ($ch);

$data =$responce;

return $data;

}

$page_data = fetchpage("www.cnn.com");

echo $page_data;

You can do the magic by using Regular Expressions on the data stored in $page_data variable.

See this post of my kind friend Mr. Siddique Ahmed on crawling guide using Simple Html DOM Class.

Happy Coding :)

Clean An Email Address

Use this function to cleanup an email address. It will remove any unwanted character smoothly.

Function:

function clean_email($email = "")
{
$email = trim($email);
$email = str_replace(" ", "", $email);

// Check for more than one @
if (substr_count($email, '@') > 1)
{
return false;
}

$email = preg_replace("#[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s]#", "", $email);

if (preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/", $email))
{
return $email;
}
else
{
return false;
}
}

Usage:

$email_address = clean_email("my!email@domain.com");

It will save "myemail@domain.com" after removing the typo mistake (probably) by user.

Happy Coding :)

Graphical Bar for Percentage Values

Following function can be used to display the percentage value (e.g Polling Result) in form of graphical bar.

Function:

function DrawBar($percentage) {
if ($percentage > 0)
{
$per = imagecreate($percentage * 3,20);
$background = imagecolorallocate($per, 0x00, 0x99, 0xFF);
$foreground = imagecolorallocate($per, 0x00, 0x8A, 0x01);
$border = imagecolorallocate($per, 0x99, 0x99, 0x99);

header("Content-type: image/png");
imagepng($per);
imagedestroy($per);
}else{
$per = imagecreate(2,20);
$background = imagecolorallocate($per, 0x00, 0x99, 0xFF);
$foreground = imagecolorallocate($per, 0x00, 0x8A, 0x01);
$border = imagecolorallocate($per, 0x99, 0x99, 0x99);

header("Content-type: image/png");
imagepng($per);
imagedestroy($per);
}
}

Usage:

DrawBar($_GET['value']);

$_GET['value'] is the percentage value which we want the function to display in graphical format. You can use this script in <img> tag also. Create a file named as graph.php and save the above code in it. Then in html portion you can call the script in the following way:

<img src="graph.php?value=75">

<img src="graph.php?value=65">

Easy and Useful!

Happy Coding :)