Archive for 'September, 2008'

How to Remove a (non-empty) Directory using PHP

Posted on September 28, 2008, Filled under PHP,  Bookmark it

Hello coders,

Here’s a snippet that can help you to remove a non-empty directory from the server. It’s a recursive function that deletes the directory with its files, folders and sub-folders.

<?php
function delete_directory($dir)
{
if ($handle = opendir($dir))
{
$array = array();

    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {

			if(is_dir($dir.$file))
			{
				if(!@rmdir($dir.$file)) // Empty directory? Remove it
				{
                delete_directory($dir.$file.'/'); // Not empty? Delete the files inside it
				}
			}
			else
			{
               @unlink($dir.$file);
			}
        }
    }
    closedir($handle);

	@rmdir($dir);
}

}

$dir = '/home/path/to/mysite.com/folder_to_delete/'; // IMPORTANT: with '/' at the end

$remove_directory = delete_directory($dir);
?>

This is a PHP Class useful if you need to resize images keeping their aspect ratio, using the GD Library. The new height is calculated proportionally to the new width’s size and reverse. For instance you have an image with the following dimensions: width – 1000, height – 800. Its thumbnail with a width of 250 will have the height of 200 (the ratio is kept).

Here’s the class (I will explain you how it works below):

resize.image.class.php

<?php
/*
---------------------------------------------------------------------
Credits: Bit Repository

Source URL: http://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html
---------------------------------------------------------------------
*/
class Resize_Image {

var $image_to_resize;
var $new_width;
var $new_height;
var $ratio;
var $new_image_name;
var $save_folder;

function resize()
{
if(!file_exists($this->image_to_resize))
{
  exit("File ".$this->image_to_resize." does not exist.");
}

$info = GetImageSize($this->image_to_resize);

if(empty($info))
{
  exit("The file ".$this->image_to_resize." doesn't seem to be an image.");
}

$width = $info[0];
$height = $info[1];
$mime = $info['mime'];

/*
Keep Aspect Ratio?

Improved, thanks to Larry
*/

if($this->ratio)
{
// if preserving the ratio, only new width or new height
// is used in the computation. if both
// are set, use width

if (isset($this->new_width))
{
$factor = (float)$this->new_width / (float)$width;
$this->new_height = $factor * $height;
}
else if (isset($this->new_height))
{
$factor = (float)$this->new_height / (float)$height;
$this->new_width = $factor * $width;
}
else
exit(”neither new height or new width has been set”);
}

// What sort of image?

$type = substr(strrchr($mime, '/'), 1);

switch ($type)
{
case 'jpeg':
    $image_create_func = 'ImageCreateFromJPEG';
    $image_save_func = 'ImageJPEG';
	$new_image_ext = 'jpg';
    break;

case 'png':
    $image_create_func = 'ImageCreateFromPNG';
    $image_save_func = 'ImagePNG';
	$new_image_ext = 'png';
    break;

case 'bmp':
    $image_create_func = 'ImageCreateFromBMP';
    $image_save_func = 'ImageBMP';
	$new_image_ext = 'bmp';
    break;

case 'gif':
    $image_create_func = 'ImageCreateFromGIF';
    $image_save_func = 'ImageGIF';
	$new_image_ext = 'gif';
    break;

case 'vnd.wap.wbmp':
    $image_create_func = 'ImageCreateFromWBMP';
    $image_save_func = 'ImageWBMP';
	$new_image_ext = 'bmp';
    break;

case 'xbm':
    $image_create_func = 'ImageCreateFromXBM';
    $image_save_func = 'ImageXBM';
	$new_image_ext = 'xbm';
    break;

default:
	$image_create_func = 'ImageCreateFromJPEG';
    $image_save_func = 'ImageJPEG';
	$new_image_ext = 'jpg';
}

	// New Image
	$image_c = ImageCreateTrueColor($this->new_width, $this->new_height);

	$new_image = $image_create_func($this->image_to_resize);

	ImageCopyResampled($image_c, $new_image, 0, 0, 0, 0, $this->new_width, $this->new_height, $width, $height);

        if($this->save_folder)
		{
	       if($this->new_image_name)
	       {
	       $new_name = $this->new_image_name.'.'.$new_image_ext;
	       }
	       else
	       {
	       $new_name = $this->new_thumb_name( basename($this->image_to_resize) ).'_resized.'.$new_image_ext;
	       }

		$save_path = $this->save_folder.$new_name;
		}
		else
		{
		/* Show the image without saving it to a folder */
		   header("Content-Type: ".$mime);

	       $image_save_func($image_c);

		   $save_path = '';
		}

	    $process = $image_save_func($image_c, $save_path);

		return array('result' => $process, 'new_file_path' => $save_path);

	}

	function new_thumb_name($filename)
	{
	$string = trim($filename);
	$string = strtolower($string);
	$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
	$string = ereg_replace("[ tnr]+", "_", $string);
	$string = str_replace(" ", '_', $string);
	$string = ereg_replace("[ _]+", "_", $string);

	return $string;
	}
}
?>

Read more from this entry…

How to Convert Text Code Smilies to Graphic Images in PHP

Posted on September 25, 2008, Filled under PHP,  Bookmark it

This is a function that modifies a text (comment) by converting the emoticons like :), :D, (Y) etc. to graphic icons.

<?php
function smilies($text, $url_address_to_images_folder) // with '/' at the end
{
$array = array(':-)' => 'smile001.gif', // happy
':)' => 'smile001.gif', // happy
':-D' => 'smile002.gif', // very happy
':D' => 'smile002.gif', // very happy
':-O' => 'smile008.gif', // surprised / o, no
':-P' => 'smile007.gif', // tongue sticking out
':P' => 'smile007.gif', // tongue sticking out
';-)' => 'smile009.gif', // wink
';)' => 'smile009.gif', // wink
':-(' => 'smile003.gif', // sad
':(' => 'smile003.gif', // sad
'8o|' => 'smile011.gif', // angry grin
':-@' => 'smile010.gif', // angry
'8-)' => 'smile027.gif', // nerd
":'(" => "smile040.gif", // crying
':-S' => 'smile005.gif', // confused
':-$' => 'smile004.gif', // embarrassed
':-|' => 'smile012.gif', // undecided
':-*' => 'smile055.gif', // kissing
':-#' => 'smile056.gif', // don't tell anyone
'(H)' => 'smile006.gif', // wacked out sunny face
'<:o)' => 'smile041.gif', // party
'(A)' => 'angel.gif', // angel
'+o(' => 'Bo.gif', // Sick
'(brb)' => 'smile043.gif', // be right back
'(6)' => 'smile039.gif', // devil
'(Y)' => 'smile049.gif', // yes
'(N)' => 'smile050.gif', // no
'(X)' => 'grl.gif', // girl
'(Z)' => 'boy.gif', // boy
'(L)' => 'smile015.gif', // love
'(U)' => 'smile016.gif', // don't love
'(K)' => 'smile020.gif', // kiss
'(P)' => 'pic.gif', // picture
'(G)' => 'gift.gif', // gift
'(%)' => 'smile037.gif', // handcuffs
'(F)' => 'smile019.gif', // flower
'(W)' => 'smile018.gif', // Wilt flower
'(D)' => 'smile036.gif', // drink
'(B)' => 'smile035.gif', // beer
'(C)' => 'coffee.gif', // cup
'(^)' => 'smile054.gif', // (Birthday) cake
'(pi)' => 'pi.gif', // pizza
'(||)' => 'smile047.gif', // chopsticks
'(M)' => 'm.gif', // messenger
'(@)' => 'cat.gif', // cat
'(sn)' => 'sn.gif', // snail
'(bah)' => 'bah.gif', // sheep
'(tu)' => 'smile042.gif', // turtel
'(&)' => 'dog.gif', // dog
':-[' => 'smile034.gif', // Bat
'(?)' => 'smile038.gif', // ASL - Age Sex Location
'({)' => 'smile026.gif', // hug left
'(})' => 'smile025.gif', // hug right
'(pl)' => 'smile048.gif', // plate
'(I)' => 'light.gif', // idea
'(8)' => 'music.gif', // music
'(ip)' => 'ip.gif', // island
'(S)' => 'smile021.gif', // asleep / moon
'(*)' => 'smile022.gif', // star
'(R)' => 'smile024.gif', // rainbow
'(#)' => 'smile023.gif', // sun
'(li)' => 'smile052.gif', // lightning
'(st)' => 'smile051.gif', // storm / rain
'(um)' => 'um.gif', // umbrella
'(co)' => 'co.gif', // computer
'(mp)' => 'mp.gif', // mobile phone
'(T)' => 'phone.gif', // telephone
'(E)' => 'mail.gif', // email
'(ap)' => 'ap.gif', // airplane
'(au)' => 'au.gif', // car
'(~)' => 'movie.gif', // movie
'(O)' => 'time.gif', // time / clock
'(so)' => 'so.gif', // soccer ball
'(ci)' => 'ci.gif', // cigarette
'(yn)' => 'smile046.gif', // fingers crossed
'(h5)' => 'smile045.gif', // high five
'(xx)' => 'smile044.gif', // x-box
'(mo)' => 'mo.gif'); // money

foreach($array as $s => $xc)
{
$text = str_replace($s, "<img align='absmiddle' src='".$url_address_to_images_folder.$xc."'>", $text);
}

return $text;
}

$text = "Hi :). This is a sample description that uses smilies :D. I hope that you will find them useful (Y).";

// 1st param: text, 2nd param: the URL address to the folder where the files are located

$text = smilies($text, 'http://www.domain.com/images/smilies/');

echo $text;
?>

smilies_sample1

Source of the emoticons: Windows Live Messenger

PHP: How to validate a telephone number

Posted on September 24, 2008, Filled under PHP,  Bookmark it

This snippet is useful if you need to validate a telephone number using an editable list with specific formats.

<?php
/*
string validate_telephone_number (string $number, array $formats)
*/

function validate_telephone_number($number, $formats)
{
$format = trim(ereg_replace("[0-9]", "#", $number));

return (in_array($format, $formats)) ? true : false;
}

/* Usage Examples */

// List of possible formats: You can add new formats or modify the existing ones

$formats = array('###-###-####', '####-###-###',
				 '(###) ###-###', '####-####-####',
				 '##-###-####-####', '####-####', '###-###-###',
				 '#####-###-###', '##########');

$number = '08008-555-555';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '123-555-555';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '1800-1234-5678';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '(800) 555-123';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '1234567890';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}
?>

How to use an image as a submit button

Posted on September 24, 2008, Filled under HTML & CSS,  Bookmark it

Greetings,

The classical submit buttons aren’t always the best choice for a form’s design. The need customized or replaced with images. In this short tutorial you will see how a submit button can be replaced with an image.

A standard submit button HTML Code will look something like this:

<input type="submit" name="submit" value="Submit">

Here’s a code that uses an image as a submit button:

<input type="image" src="http://www.yoursite.com/images/myimage.gif">

As you can see, the SRC attribute has been added containing the URL address of the image and the TYPE’s value was changed to ‘image’.

Good luck!

PHP: Check (validate) if the Uploaded File is an Image

Posted on September 24, 2008, Filled under PHP,  Bookmark it

In this tutorial I will show you how to create an image validator script. You can choose between 2 methods of validation: one that will verify if the file is actually an image, by checking the file’s mime-type, and the other one which checks the extension of the uploaded file.

Let’s start creating the configuration file:

config.php

<?php
/*
1 = Check if the file uploaded is actually an image no matter what extension it has
2 = The uploaded files must have a specific image extension
*/

$validation_type = 1;

if($validation_type == 1)
{
	$mime = array('image/gif' => 'gif',
                  'image/jpeg' => 'jpeg',
                  'image/png' => 'png',
                  'application/x-shockwave-flash' => 'swf',
                  'image/psd' => 'psd',
                  'image/bmp' => 'bmp',
                  'image/tiff' => 'tiff',
                  'image/tiff' => 'tiff',
                  'image/jp2' => 'jp2',
                  'image/iff' => 'iff',
                  'image/vnd.wap.wbmp' => 'bmp',
                  'image/xbm' => 'xbm',
                  'image/vnd.microsoft.icon' => 'ico');
}
else if($validation_type == 2) // Second choice? Set the extensions
{
	$image_extensions_allowed = array('jpg', 'jpeg', 'png', 'gif','bmp');
}

$upload_image_to_folder = 'images/';
?>

Now let’s create the form that will help us to upload the file:

<form enctype="multipart/form-data" action="validate_image_upload.php" method="POST">

<!-- MAX_FILE_SIZE must be set before the input element -->
<input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

<!-- The name from the $_FILES array is determined by the input name -->
Select an Image: <input name="image_file" type="file" />
<input type="submit" value="Upload" />

</form>

Our form will send the data to validate_image_upload.php. Here, the script will check the type of validation. If the file is validated the user will see a successful submission message and the file will be moved in the specified image folder. The uploaded file failed to pass the validation process? In this case, it will be deleted and the script will output an error message.

Read more from this entry…

Hello coders,

This is a PHP Class that calculates the size, number of files & folders of a specific directory.

calculate.directory.class.php

<?php
/*
Credits: BitRepository.com
URL: http://www.bitrepository.com/web-programming/php/calculate-the-size-number-of-files-folders-of-a-directory.html
*/

class Directory_Calculator {

    var $size_in;
	var $decimals;

    function calculate_whole_directory($directory)
    {
        if ($handle = opendir($directory))
        {
        $size = 0;
		$folders = 0;
		$files = 0;

        while (false !== ($file = readdir($handle)))
		{
            if ($file != "." && $file != "..")
			{
			    if(is_dir($directory.$file))
			    {
                $array = $this->calculate_whole_directory($directory.$file.'/');
                $size += $array['size'];
				$files += $array['files'];
				$folders += $array['folders'];
			    }
			    else
			    {
                $size += filesize($directory.$file);
				$files++;
			    }
            }
         }
         closedir($handle);
         }

		 $folders++;

    return array('size' => $size, 'files' => $files, 'folders' => $folders);
    }

	function size_calculator($size_in_bytes)
    {
        if($this->size_in == 'B')
        {
        $size = $size_in_bytes;
        }
        elseif($this->size_in == 'KB')
        {
        $size = (($size_in_bytes / 1024));
        }
        elseif($this->size_in == 'MB')
        {
        $size = (($size_in_bytes / 1024) / 1024);
        }
        elseif($this->size_in == 'GB')
        {
        $size = (($size_in_bytes / 1024) / 1024) / 1024;
        }

        $size = round($size, $this->decimals);

		return $size;
	}

	function size($directory)
	{
	$array = $this->calculate_whole_directory($directory);
	$bytes = $array['size'];
	$size = $this->size_calculator($bytes);
	$files = $array['files'];
	$folders = $array['folders'] - 1; // exclude the main folder

	return array('size'    => $size,
		         'files'   => $files,
		         'folders' => $folders);
	}
}
?>

Read more from this entry…

How to add a stylish icon into a (form) text box

Posted on September 22, 2008, Filled under HTML & CSS,  Bookmark it

Greetings,

This CSS Code is useful if you need to add a stylish icon into a text box inside a form. Many sites use this sort of inputs. Here’s an example of a login page using this style:

stylish-icon-into-a-form-text-box

To see how the icons are added in the input text box check this css code:

.textbox_username
{
background: #ffffff url('images/icon_username.png') no-repeat;
background-position: 1 1;

padding-left: 19px;

border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

color: #333333; 

font: 90% Verdana, Helvetica, Arial, sans-serif;

font-size: 12px;

height: 20px;
}

.textbox_password
{
background: #ffffff url('images/icon_password.png') no-repeat;
background-position: 1 1;

padding-left: 19px;

border: 1px solid #999999;
border-top-color: #CCCCCC;
border-left-color: #CCCCCC; 

color: #333333; 

font: 90% Verdana, Helvetica, Arial, sans-serif;

font-size: 12px;

height: 20px;
}

Read the rest of this entry…

Creating stylish pagination links

Posted on September 21, 2008, Filled under HTML & CSS,  Bookmark it

Do you want to add some style to your pagination links? If so, then the following CSS Codes can help you to do that. The links should be placed inside a DIV (as it is in our example) which can be easily customized. There are cases when some navigation links are not required, such as “next” (when there are no further pages) or “previous” (when the first page is selected). You can hide or place them between the following tags to mark that they are disabled: <span class=”disabled”>Previous</span>.

First Style

<style type="text/css">

<!--
/*
Credits: BitRepository.com
*/

html, body {
background-color: white; 

color: #2B3956;
font-family: Verdana, Arial, Sans-Serif;
font-size: 11px;
text-align: left;
}
/* Pagination DIV */
#pg
{
width: 700px;
background-color: #FFFFFF;

text-align: center;
font-size: 10px;

margin-bottom: 5px;

padding: 10px;
}

/* Pagination Link */

#pg a {
font-size: 10px;
text-decoration: none;
color: #000000;
border: 1px solid #dddddd;
padding: 3px;
-moz-border-radius: 3px;
}

#pg a:hover {
font-size: 10px;
text-decoration: none;
color: #000000;
border: 1px solid #A7A7A7;
background-color: white;
padding: 3px;
-moz-border-radius: 3px;
}

/* Pagination Current Page */

#pg a.current {
font-size: 10px;
text-decoration: none;
color: #000000;
border: 1px solid #336699;
background-color: #F5F7FA;
padding: 3px;
-moz-border-radius: 3px;
}

/* Pagination Disabled Page */

#pg span.disabled {
font-size: 10px;
text-decoration: none;
color: #C6C7C7;
border: 1px solid #C6C7C7;
background-color: white;
padding: 3px;
-moz-border-radius: 3px; // Rounds the corners; Works for Mozilla only
}
-->
</style>

Read more from this entry…