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 = ' ';
// Display items in random order?
$random_order = true;
?>
functions.php
This function is used to randomly reorder the elements of an array.
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%.
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.
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’).
<?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.
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);
?>
Posted on September 28, 2008, Filled under PHP, Bookmark it
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;
}
}
?>
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.