Archive for 'September, 2008'

PHP: How to center a text on an image using GD

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

Hello coders,

This is a snippet which centers a text on an image using the GD Library.

First, we create the image using the ImageCreate() function. Here we set the width & height.

$width = 400;
$height = 100;

$im = ImageCreate($width, $height);

The we use ImageColorAllocate() to fill the image with white background and set the border’s color, which is eventually created with ImageRectangle().

// white background and blue text
$bg = ImageColorAllocate($im, 255, 255, 255);

// grey border
$border = ImageColorAllocate($im, 207, 199, 199);
ImageRectangle($im, 0, 0, $width - 1, $height - 1, $border);

Set the text and its color:

$text = 'This is my photo description text.';

$textcolor = ImageColorAllocate($im, 0, 0, 255);

Read more from this entry…

Validating an image upload

Posted on September 8, 2008, Filled under JavaScript,  Bookmark it

This is a useful JavaScript function which validates an image upload by checking the extension of the file that should be uploaded. If the extension is jpg, jpeg, png or gif it will return true. Otherwise, it will return false.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>Validate image on upload @ BitRepository.com</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="validate, extensions, file, javascript">
  <META NAME="Description" CONTENT="A JavaScript Extension Validator for Images">

<SCRIPT LANGUAGE="JavaScript">

<!--
function validate()
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");

/*
// Alternative way to create the array

var extensions = new Array();

extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/

var image_file = document.form.image_file.value;

var image_length = document.form.image_file.value.length;

var pos = image_file.lastIndexOf('.') + 1;

var ext = image_file.substring(pos, image_length);

var final_ext = ext.toLowerCase();

for (i = 0; i < extensions.length; i++)
{
    if(extensions[i] == final_ext)
    {
    return true;
    }
}

alert("You must upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
 //-->

 </SCRIPT>

 </HEAD>

<BODY>

<center>

<form name="form" action="http://www.microsoft.com" enctype="multipart/form-data" method="post" onSubmit="return validate();">

<h2>Validate image on upload</h2>

<br />

	Upload an image: <INPUT type="file" name="image_file"> <input type="submit" name="submit" value="Submit">

</form>

</center>

</BODY>

</HTML>

NOTE: You can add more extensions to the validator by continuing the extensions array.

Good luck!


PHP: Get Main Base URL

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

This is a snippet which extracts the Main Base Address from a complete URL:

<?php
function GetMainBaseFromURL($url)
{
$chars = preg_split('//', $url, -1, PREG_SPLIT_NO_EMPTY);

$slash = 3; // 3rd slash

$i = 0;

foreach($chars as $key => $char)
{
	if($char == '/')
	{
	   $j = $i++;
	}

	if($i == 3)
	{
	   $pos = $key; break;
	}
}

$main_base = substr($url, 0, $pos);

return $main_base.'/';
}

$url = 'http://mysubdomain.mydomain.com/category/hardware/subcategory/mainboards.html';

$main_base = GetMainBaseFromURL($url);

// Output: http://mysubdomain.mydomain.com/

echo $main_base;
?>

PHP: Get Base (Directory) From File (URL, Path)

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

If you need to determine the base element from a URL or path of a file then this snippet can help you.

<?php
/*
Source: http://www.bitrepository.com/
*/
function Get_Base_From_File($file)
{
$find = '/';

$after_find = substr(strrchr($file, $find), 1);

$strlen_str = strlen($after_find);

$result = substr($file, 0, -$strlen_str);

return $result;
}

$file = 'http://www.domain.com/path/to/file.zip';

$base = Get_Base_From_File($file);

// Output: http://www.domain.com/path/to/
echo $base;
?>

PHP: Using the string concatenation

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

Here are some simple examples of string concatenation:

<?php
$first_name = 'John';
$last_name = 'Jones';
$work_area = 'IT Industry';

$text = 'His name is '.$first_name.' '.$last_name.' and he is working in the '.$work_area;

// Output: His name is John Jones and he is working in the IT Industry
echo $text;
?>

How to emphasize specific words from a string (text)

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

This function can help you to emphasize specific words from a simple (non-html) text. You can currently choose between 3 ways of emphasis: bold, underline, highlight. You can also add your own method of emphasis if you add more ELSE IFs with the ‘type’ and ‘css property’.

<?php
/*
---------------------------------------
Credits: Bit Repository
    URL: http://www.bitrepository.com/
---------------------------------------
*/

function emphasize_specific_words($str, $words, $type = 'highlight')
{
if($type == 'highlight')
{
$var_style = 'background: #CEDAEB;';
}
else if($type == 'bold')
{
$var_style = 'font-weight: bold;';
}
else if($type == 'underline')
{
$var_style = 'text-decoration: underline;';
}

if(is_array($words))
{
	foreach($words as $word)
	{
		if(strlen($word) <= 1)
		{
			continue;
		}
		if($word)
		{
$word= strip_tags($word);
$word= preg_quote($word, '/');

$str = preg_replace('/'.$word.'/i',
"<span style='".$var_style."'>".$word."</span>",$str);
		}
	}

    return $str;
}
else
	{
	return false;
	}
}

$str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Sed id eros sit amet lorem consectetuer volutpat.
Ut egestas congue magna. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit.
Nunc sapien. Quisque fermentum dui sed velit. Nulla eget eros.
Cras tristique vulputate sapien.";

# Words to emphasize (should be an array)

$words = array('Lorem', 'consectetuer', 'amet',
'fermentum', 'tristique', 'vulputate'); 

# 1st argument: the text
# 2nd argument: the keywords array
# 3rd argument: the type of emphasis (bold, underline, highlight)

// tags from $words are automatically stripped
$string = emphasize_specific_words($str, $words, 'bold');

echo $string;
?>

Here's the output of our example:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Sed id eros sit amet Lorem consectetuer volutpat.
Ut egestas congue magna. Lorem ipsum dolor sit amet,

consectetuer adipiscing elit.
Nunc sapien. Quisque fermentum dui sed velit. Nulla eget eros.
Cras tristique vulputate sapien.

You can also check our keywords highlighter if you want to highlight your keywords in your search results.

How to extract username from an e-mail address string

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

If you need to extract the username from an e-mail address string then this snippet can help you. For instance, you can use this function inside a loop, while selecting emails from a database.

<?php
function getUsernameFromEmail($email)
{
$find = '@';
$pos = strpos($email, $find);

$username = substr($email, 0, $pos);

return $username;
}

$email = 'thecoder@domain.com';

$username = getUsernameFromEmail($email);

echo $username; // thecoder
?>

If, for any reason, you need to extract the domain from an e-mail address (or from multiple e-mail address that are in a database) then you can use this function:

<?php
function getDomainFromEmail($email)
{
// Get the data after the @ sign
$domain = substr(strrchr($email, "@"), 1);

return $domain;
}

// Example

$email = 'the_username_here@yahoo.com';

$domain = getDomainFromEmail($email);

echo $domain; // yahoo.com
?>

This is a very useful snippet if you need to see the complete content of a directory (files, folders, subfolders). The function is defined and applied within its own definition each time folders are found. It’s a recursive function which traverses through the subdirectories until it cannot go any farther.

<?php
/*
Source: Bit Repository
URL: http://www.bitrepository.com/
*/
function read_whole_directory($dir)
{
if ($handle = opendir($dir))
{
$array = array();

    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
			if(is_dir($dir.$file))
			{
                $array[][$file] = read_whole_directory($dir.$file.'/');
			}
			else
			{
                $array[] = $file;
			}
        }
    }
    closedir($handle);
}

if(is_array($array))
	{
	return $array;
	}
	else
	{
	return false;
	}
}

$dir = '/your/path/to/public_html/'; // IMPORTANT: with '/' at the end

$directory = read_whole_directory($dir);

echo "<pre>"; print_r($directory); echo "</pre>";
?>

NOTE: Make sure your directory string has ‘/’ at the end.