Browse: PHP

Open Source Applications, Tutorials, Snippets

PHP: How to create a Tag Cloud

Posted on October 3, 2008, Filled under PHP,  Bookmark it

This is a tutorial that will give you an idea of how to create a Tag Cloud and implemented it the pages of your website.

Let’s start creating the necessary files:

config.php

The $factor variable is used in the mathematical operation which calculates the importance of a tag (index.php, line 81). It calculates the average text size of the tags. Increasing this value will make the text size to increase as well. Decreasing will do reverse.

In $starting_font_size we set the minimal font size that a tag can have. This variable is also used to calculate the importance of the tag.

We need a separator that will be placed between the tags. In $tag_separator its value must be set.

Do you wish to show the tags in random order? Set $random_order to TRUE (if yes) or FALSE (if not).

<?php
// Incresing this number will make the words bigger;
// Decreasing will do reverse

$factor = 0.5;

// Smallest font size possible

$starting_font_size = 12;

// Tag Separator

$tag_separator = '&nbsp; &nbsp; &nbsp;';

// Display items in random order?

$random_order = true;
?>

functions.php

This function is used to randomly reorder the elements of an array.

<?php
function randomize_array($array)
{
$rand_items = array_rand($array, count($array));

$new_array = array();

foreach($rand_items as $value)
	{
	$new_array[$value] = $array[$value];
	}

	return $new_array;
}
?>

Let’s add some style to our tag cloud!

style.css

HTML, BODY
{
padding: 0;
border: 0px none;
font-family: Verdana;
font-weight: none;
}

.tags_div
{
padding: 3px;
border: 1px solid #A8A8C3;
background-color: white;
width: 500px;
-moz-border-radius: 5px;
}

H1
{
font-size: 16px;
font-weight: none;
}

A:link
{
color: #676F9D;
text-decoration: none;
}

A:hover
{
text-decoration: none;
background-color: #4F5AA1;
color: white;
}

index.php

For our tag cloud sample I’ve used a list of top programming languages from TIOBE Software.

The list is stored in an array ($languages) that contains the names of the programming languages (the keys of the array) and their ratings (the values of the array). The second array, $languages_wiki is used to set links for our tags (the addresses are from Wikipedia having information about the programming languages from the list).

As you can see the total sum of the values is calculated (in our case it’s 94.732). This is used in the mathematical operation that will calculate the importance of a tag. It’s obvious that JAVA (20.715), compared to Delphi (3.130), is a more important tag representing 22% from the total sum of the ratings, while Delphi only 3%.

<?php
include_once 'config.php';
include_once 'functions.php';

$languages = array('PHP'            => '9.243',
                   'Python'         => '5.012',
                   'ActionScript'   => '0.472',
                   'Lisp/Scheme'    => '0.419',
                   'Lua'            => '0.415',
                   'Pascal'         => '0.400',
                   'Java'           => '20.715',
                   'PowerShell'     => '0.384',
                   'COBOL'          => '0.360',
                   'SAS'            => '0.640',
                   'JavaScript'     => '3.130',
                   'PL/SQL'         => '0.700',
                   '(Visual) Basic' => '10.490',
                   'D'              => '1.265',
                   'Ruby'           => '2.762',
                   'Delphi'         => '3.055',
                   'C#'             => '4.334',
                   'Perl'           => '4.841',
                   'C++'            => '10.716',
                   'C'              => '15.379');

$languages_wiki = array('PHP'       => 'PHP',
                   'Python'         => 'Python_(programming_language)',
                   'ActionScript'   => 'ActionScript',
                   'Lisp/Scheme'    => 'Lisp_(programming_language)',
                   'Lua'            => 'Lua_(programming_language)',
                   'Pascal'         => 'Pascal_Programming_Language',
                   'Java'           => 'Java',
                   'PowerShell'     => 'PowerShell',
                   'COBOL'          => 'COBOL',
                   'SAS'            => 'SAS_programming_language',
                   'JavaScript'     => 'JavaScript',
                   'PL/SQL'         => 'PL/SQL',
                   '(Visual) Basic' => 'Visual_Basic',
                   'D'              => 'D_programming_language',
                   'Ruby'           => 'Ruby',
                   'Delphi'         => 'Delphi',
                   'C#'             => 'C_Sharp_(programming_language)',
                   'Perl'           => 'Perl',
                   'C++'            => 'C%2B%2B',
                   'C'              => 'C_programming');

$max_count = array_sum($languages);

if($random_order)
{
$languages = randomize_array($languages);
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> Tag Cloud Generator </TITLE>

  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="tag, cloud">
  <META NAME="Description" CONTENT="A Tag Cloud Example">

<LINK REL="stylesheet" HREF="style.css" TYPE="text/css">

 </HEAD>

 <BODY>

 </BODY>
</HTML>

<!-- Add some style to the DIV -->

<center><h1>Tag Cloud Example</h1><div align='center' class='tags_div'>

<?php
foreach($languages as $language => $rating)
{
$x = round(($rating * 100) / $max_count) * $factor;

$font_size = $starting_font_size + $x.'px';

echo "<span style='font-size: ".$font_size."; color: #676F9D;'>
<a href='http://en.wikipedia.org/wiki/".$languages_wiki[$language]."'>".$language."</a></span>".$tag_separator;
}
?>

</div></center>

Example #1 (with factor equal with 0.5)

Example #2 (with factor equal with 1 and mouse cursor over ‘Ruby’)

You can use this model to create tag clouds from arrays that are created from MySQL Selects or from Flat Files Databases.

Display Values from an Array in Random Order

Posted on October 2, 2008, Filled under PHP,  Bookmark it

This is a function that randomizes the order of the elements in an array.

<?php
function randomize_array($array)
{
$rand_items = array_rand($array, count($array));

$new_array = array();

foreach($rand_items as $value)
	{
	$new_array[$value] = $array[$value];
	}

	return $new_array;
}

$array = array('sleep' => 'Delay execution',
                    'show_source' => 'alias for highlight_file()',
                    'str_ireplace' => 'PHP5 Function',
                    'sizeof' => 'Alias for count',
                    'parse_url' => 'Parse a URL and return its components');

echo "<pre>"; print_r($array); echo "</pre>";

echo "<pre>"; print_r(randomize_array($array)); echo "</pre>";

/*
-- Initial Array

Array
(
    [sleep] => Delay execution
    [show_source] => alias for highlight_file()
    [str_ireplace] => PHP5 Function
    [sizeof] => Alias for count
    [parse_url] => Parse a URL and return its components
)

-- An example of a random result

Array
(
    [sizeof] => Alias for count
    [parse_url] => Parse a URL and return its components
    [sleep] => Delay execution
    [str_ireplace] => PHP5 Function
    [show_source] => alias for highlight_file()
)
*/
?>

NOTE: A similar function in PHP is shuffle() which assigns new keys to elements in the array. It removes any existing keys that may have been assigned, instead of just reordering them as our randomize_array() function does.

PHP: Cropping a Rectangle Image to Square using GD

Posted on October 1, 2008, Filled under PHP,  Bookmark it

Hello coders,

This is a PHP Class that crops images (rectangles) to squares using the GD library. First, make sure you have this extension enabled. This can be verified using the following code:

check_gd.php

<?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit("The GD extension is not loaded.");
    }
}
?>

The class checks if the image is already a square. If it is, it will output a message to the user. If it’s not it will calculate the necessary coordinates and crop it: to left, center or right (default is ‘center’).

crop.image.to.square.class.php

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

Source URL: http://www.bitrepository.com/web-programming/php/crop-rectangle-to-square.html
--------------------------------------------------------------------------------------------
*/ 

/* Crop Image Class */

class Crop_Image_To_Square {

var $source_image;
var $new_image_name;
var $save_to_folder;

function crop($location = 'center')
{
$info = GetImageSize($this->source_image);

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

if($width == $height)
{
echo 'The source image is already a square.';
}
else
{
// 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';
}

// Coordinates calculator

   if($width > $height) // Horizontal Rectangle?
   {
	   if($location == 'center')
       {
       $x_pos = ($width - $height) / 2;
       $x_pos = ceil($x_pos);

       $y_pos = 0;
	   }
	   else if($location == 'left')
	   {
	   $x_pos = 0;
	   $y_pos = 0;
	   }
	   else if($location == 'right')
	   {
	   $x_pos = ($width - $height);
	   $y_pos = 0;
	   }

       $new_width = $height;
       $new_height = $height;
   }
   else if($height > $width) // Vertical Rectangle?
   {
	   if($location == 'center')
       {
       $x_pos = 0;

       $y_pos = ($height - $width) / 2;
       $y_pos = ceil($y_pos);
       }
	   else if($location == 'left')
	   {
	   $x_pos = 0;
	   $y_pos = 0;
	   }
	   else if($location == 'right')
	   {
	   $x_pos = 0;
	   $y_pos = ($height - $width);
	   }

       $new_width = $width;
       $new_height = $width;

   }

$image = $image_create_func($this->source_image);

$new_image = ImageCreateTrueColor($new_width, $new_height);

// Crop to Square using the given dimensions
ImageCopy($new_image, $image, 0, 0, $x_pos, $y_pos, $width, $height);

if($this->save_to_folder)
		{
	       if($this->new_image_name)
	       {
	       $new_name = $this->new_image_name.'.'.$new_image_ext;
	       }
	       else
	       {
	       $new_name = $this->new_image_name( basename($this->source_image) ).'_square_'.$location.'.'.$new_image_ext;
	       }

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

	       $image_save_func($new_image);

		   $save_path = '';
		}

// Save image 

$process = $image_save_func($new_image, $save_path) or die("There was a problem in saving the new file.");

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

function new_image_name($filename)
	{
	$string = trim($filename);
	$string = strtolower($string);
	$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
	$string = ereg_replace("[ \t\n\r]+", "_", $string);

	$string = str_replace(" ", '_', $string);
	$string = ereg_replace("[ _]+", "_", $string);

	return $string;
	}
}
?>
Variables Info

$source – Here we set the full path (i.e. /home/www.mysite.com/public_html/images/myrectangle.jpg) to the rectangle image we wish to crop. If the image is in the same folder with the class, then you can just set the filename as the path (i.e. myrectangle.jpg).

$new_image_name – It’s used to set a name for the new cropped image. If it’s not set a name will be assigned automatically.

$save_to_folder – The path to the folder where the square image will be saved. Make sure it’s writable (0777). It no folder is set the new square image will show in the browser (on the fly) without being saved.

This is an usage example of this class:

example.php

<?php
include 'crop.image.to.square.class.php';

$crop = new Crop_Image_To_Square;
$crop->source_image = 'my_rectangle_image.jpg';

$crop->save_to_folder = 'square_images/';

/* left, center or right; If none is set, center will be used as default */
$process = $crop->crop('right');

if($process['result'])
{
echo 'The rectangle image ('.$process['new_file_path'].') was cropped.';
}
?>

If you’re interested in resizing an image (i.e. to square) consider checking our post regarding images resizing.

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.';
}
?>

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…