Tag Archives: Programming

Email Address Validation in PHP

One of the most common values that needs validation in PHP is the email address. You use this to signup for about 95% of websites. Email address validation isn’t necessarily difficult but if you’re unfamiliar with regular expressions and aren’t currently using a pre-built validation class or some other type of validation library, it can be tricky.

I’m here to solve all of that for you with a simple function, check it out:

function is_valid_email ($address) {
return (preg_match(
'/^[-!#$%&'*+\./0-9=?A-Z^_`{|}~]+'.
'@'.
'([-0-9A-Z]+.)+' .
'([0-9A-Z]){2,4}$/i',
trim($address)));
}

Using the email address validation function

/**
* Check if this email address validates
*/
if (is_valid_email($_REQUEST['email_address_here'])) {
/**
* It's a valid email address!
*/
} else {
/**
* It's an invalid email address!
*/
}

It’s as simple as that! I’ve tested it with a lot of email addresses thus far, so if you find any it can’t validate let me know.

Stuff that’s easy should be easier than stuff that’s easier than it.
Bryan

Crop an Image with PHP

I spent a few minutes working on this function that lets me crop the center of an image by width and height. Sometimes you want to create a photo gallery and use album covers for the image that links to the gallery page. Most of the time you want these images to be of a uniform size, i.e. thumbnails. This function (crop_image()) crops an image equally proportioned in the center depending on the size you give it.

Side note: If the spacing in the code is still FUBAR’d when you read this, sorry, I don’t know wtf’s up with my syntax highlighter, but I’m working on it.

Requirements for this to work properly (strictly recommended)

  • PHP 5.2.x (at least, however I’m pretty sure it will work in PHP 4)
  • GD 1.8

The function

/**
* @copyright crainbandy.com
* @since November 6th, 2008
* @author bryan maxwell - www.crainbandy.com
* --------------------------
* @name crop_image
* @package image editing
* @subpackage cropping
* --------------------------
* @link http://www.crainbandy.com/2008/11/06/crop-an-image-with-php/434
*
* This is a function that allows you to take any image $image and crop it to a specific size.
*
* @example crop_image('images/something.jpg', 'images/cropped.jpg', 125, 125);
*
* $_SERVER['DOCUMENT_ROOT'] is included on all image paths.
*
* @param string $src_image
* @param int $width
* @param int $height
* @param bool $cropped_image
* @param bool $link
* @return either true if it worked, or false if it didn't. or a string link to the image that has been cropped depending on $link's value.
*/
function crop_image($src_image, $width, $height, $cropped_image = false, $link = false) {
/**
* Setup some variables
*/
$dir = dirname($src_image);
$image_filename = $src_image;

/**
* Get the extension
*/
$len 		= strlen($image_filename);
$extension 	= substr($image_filename, $len - 4, $len);

/**
* Create the handles
*/
$src_file = $_SERVER['DOCUMENT_ROOT'] . $image_filename;

/**
* What kind of file is it?
* --
* Clean it up a bit, then instantiate the image.
*/
$clean_extension = str_replace('.', '', $extension);
switch ($extension) {
case '.jpg':
case '.gif':
case '.png':
/**
* Use a variable as a function name to call it, dynamically.
*/
$type = ($clean_extension == 'jpg') ? 'jpeg' : $clean_extension;
$dynamic_function = "imagecreatefrom$type";
break;
}
$src  = $dynamic_function($_SERVER['DOCUMENT_ROOT'] . $image_filename);
$dest = imagecreatetruecolor($width, $height);

/**
* Are we renaming this? or just following suit with $src_image appending to it?
*/
if (!$cropped_image) {
$cropped_image = $_SERVER['DOCUMENT_ROOT'] . str_replace($extension, '_cropped' . $extension, $image_filename);
} else {
$cropped_image = $_SERVER['DOCUMENT_ROOT'] . "/$dir/$cropped_image";
}

/**
* Get size of the $src_file
*/
$size_array = getimagesize($src_file);

/**
* Set the size of the crop from the image.
*/
$crop_width  = 125;
$crop_x 	 = $crop_width / 2;
$crop_height = 125;
$crop_y 	 = $crop_height / 2;

/**
* Set original sizes
*/
$original_width  = $size_array[0];
$original_height = $size_array[1];

/**
* Logic
*/
if ($crop_width > $original_width || $crop_height > $original_height) {
die('Image dimensions are too big for the crop x-y you provided.');
}

/**
* Output the image
*/
imagecopy($dest, $src, 0, 0, $crop_x, $crop_y, $original_width, $original_height);
switch ($extension) {
case '.jpg':
case '.gif':
case '.png':
$dynamic_function = "image$type";
$result = $dynamic_function($dest, $cropped_image);
break;
}

/**
* Little bit of error control.
*/
if ($result) {
if ($link) {
return $cropped_image;
} else {
return true;
}
}

/**
* Trash.
*/
imagedestroy($dest);
}

How to use it

The function has five basic parameters. Three of which are required.

  1. src_image
    This is the relative path, including file name of the image you want to crop. $_SERVER['DOCUMENT_ROOT'] is appended already, so you can leave that out.
  2. width
    This is the width of the crop.
  3. height
  4. This is the height of the crop.

Two that are optional

  1. cropped_image
    This is the relative path to the output file including file name.
    Note: If you leave this blank it will append cropped_ to the src_image. image.jpg becomes cropped_image.jpg.
  2. link
    If yes, this will return the path to the cropped image.

Examples

This file is included with the download at the end of this article. You can reference these again in examples.php if you need.

/
**
* @copyright www.crainbandy.com
* @author bryan maxwell
*
* Crop image examples
*/
include('crop_image.function.php');

/**
* Crop an image to 125px by 125px.
*/
crop_image('uncropped_images/crop_me.jpg', 125, 152, 'cropped_images/i_got_cropped.jpg');

/**
* Crop an image 50x50 using the functions default naming convention
*/
crop_image('images/something.jpg', 50, 50);

/**
* Crop an image 25x25 using all properties.
*/
$cropped_image = crop_image('image.jpg', 25, 25, 'cropped.jpg', true);
echo "<img src="" alt="" />";

/**
* Crop an image 100x100 using the link function, but default naming.
*/
echo crop_image('image.jpg', 100, 100, false, true);

There you go, I hope you’re getting the hang of it.

Download

RAR Format (.rar) | Zip format (.zip)

Enjoi. If you have any questions please post in the comments. Spanks. Oh yeah, and DIGG IT.
Bryan

Humanized Enso – Command line meets GUI

Humanized Enso

Last night as I was perusing the series of tubes I went to one of the sites I frequent, Mozilla Labs. I was looking for some design inspiration for Crainbandy, some inspiration, and I wanted to mix it with a little bit of bad ass. I was reading through the archives and that’s when I found Enso. The post I found Enso from was about The Graphical Keyboard User Interface. Allow me to link it up. It’s a good read, go read it. Would you seriously go read it already? Alright. Tappin’ out. Wait, one last thing. I’ve used this program for less than 24 hours, and I promise you I will never have a PC again without Enso on it.

Dominantly the article covers a lot of good stuff, but Enso was what gave me the chubby, and the idea that command line is lightyears quicker than a GUI. Combine them both, and you have Enso. Humanized (creators of Enso) have a similar article that’s also worth reading. I’m not a command line fan boy, but I am definitely an advocate for both a GUI and a command line esque functionality that is encompassed in a no-brainer type execution structure. (COUGH) Enso.

Side note

I am addicted to Enso after just a day of use, but Mozilla Labs has an extremely good idea ironically called Ubiquity. Ubiquity is going exactly in the same direction as Enso, it’s just geared much more towards connecting the series of tubes.

Here’s a video of Ubiquity in action

What is Enso?


Excerpt from Humanized Enso site
Having to change programs to perform simple tasks—for example, making a quick calculation, or looking up a definition—breaks your concentration, takes you away from the task at hand, and wastes your valuable time. Enso lets you do common computing tasks easier and faster than ever before. You get a huge productivity boost and a simpler digital life. And now that Enso is free, it won’t cost you a penny.

Turning Caps Lock into a command key might sound strange at first — no other software works that way, does it? — but our philosophy is that interfaces can’t hope to be better than what you’re used to unless they’re different from what you’re used to. You’ll find that Enso is different in a lot of other ways, too. Give the Caps Lock method a try. If you don’t like it, you can of course configure Enso to be activated in the way you prefer

How does Enso work?

(Warning: Nutshell.)

  • Install it on your PC and fire up Enso Launcher
  • Press and hold “CAPS LOCK” to enable the Enso prompt
  • If all else fails hold down CAPS LOCK and type “help”

It’s that easy, let me give you some examples.

Take this in its for instance

Some common tasks that Enso makes blazing fast. One neat thing about Enso is that it has a dictionary index that it searches through for each keystroke you type in the prompt. If you type “o” it would show you all the commands that have the letter “o” in them. You can type “help” at any time to visit the help page that’s hosted on your machine. If that’s not enough you can also view the command list by typing “command list”

The coolest thing about all of this is, you type a small portion of the command you want to run, and Enso finds the most suitable. To execute that command you simply release the CAPS LOCK key. If you messed up and didn’t input what you wanted, simply slam all your fingers into your keyboard at once (shit tons of fun) and watch Enso quickly run out of options resulting in a beautiful notice of “Command not found”

Note

All of these examples assume I’m holding down CAPS LOCK before I type the command.

  • Opening Firefox
    Long version: open mozilla firefox
    Short version: open fir
  • Opening iTunes
    Long version: open itunes
    Short version: open it
  • Going to a window
    go itunes
    go skype
  • Minimize/Maximize/Close window manipulation
    close
    maximize
    minimize

Here’s some screenshots of Enso, and here’s a video of it in action

Developers and Beta

Now we’re getting to the cool part. Enso has created extensions to it’s framework allowing you to:

  • Enso Media Remote Control – A remote-control for your music: Play, pause, and skip tracks in your favorite music player from any application.
  • Enso Words – Spell check, and word definitions on the fly.
  • Enso Developer Prototype – Lets developers write their own Enso commands. (omfg)

I’m only listing half of the extensions they have available. If you sit infront of a computer the majority of your day, do yourself a favor. There’s a lot in this article I didn’t cover for longevity’s sake, and yours. They have done an outstanding job of making it easy to use, and understand. Just start using it and within hours you know what you’re doing. Stay tuned though, I will be writing tutorials for Enso and Ubiquity developers soon.

Once you install Enso, you won’t ever uninstall it.

Download it

You don’t even know what you’re missing.
Bryan

Data sanitization in PHP

I’m going to show you a simple, yet effective way to clean your data (sanitize it) before you attempt to insert into your database. I prefer using the $_REQUEST superglobal array instead of just $_POST or $_GET.

$_REQUEST encompasses $_GET, $_POST, and $_COOKIE inside one array.

We take the $_REQUEST array and do a foreach() loop over it assigning $k for the key and $v for the value of the array element we’re currently looping over. We then re-assign the value to the array after we have cleaned it.

foreach($_REQUEST as $k => $v) {
    $_REQUEST[$k] = addslashes($v);
}

You’re not limited to just the $_REQUEST array, you can use this method on any array that you need to perform specific actions on. There’s even functions built-in to PHP such as array_walk() that allow you to iterate over an array issuing callbacks on each element. The choice is up to you, I just prefer the simplest method.

Sanitization is not the same as validation.

The elephants instep,
Bryan

Templates & PHP together in harmony

NOTE: There were a couple bugs in this code, but they’ve been fixed. Feel free to copy and paste this code (following the instructions), and test for yourself. The newly corrected code is in bold.

So a lot of people ask me how I seperate “business logic” from “display logic” in my sites and just in general. Usually you have two options, well, the third one (which i’m not going to show) pretty much defeats the purpose but don’t worry about that.

The first choice you have is to create functions referred to sometimes as “get” functions, such as the following:
<title><?php get_title(); ?></title>
or something like <?php get_pages_content($active_page); ?> you get the point. These functions are very specific and are obviously pre-built.

Second choice you have is to create a template file and make it with real content and then replace it with template variables encased in curly braces. Like {THIS} and {THIS_VARIABLE} actually, you can use whatever you want to encase the variables in dashes, brackets, percent symbols. Just for the record I use curly braces. Basically what you’re going to end up doing is replacing the variables with values and then echoing the entire file. It’s cool, so, check it out.

This whole routine is going to take 3 files.

  1. A template file (template.tpl)
  2. a class to handle the template file (the template class, this will be inside template.class.php)
  3. an index.php page to initialize the class and draw the data.

For the sake of length, I’m going to use the second method (The first one is too difficult and not as efficient)
Step 1 – Create the template file (usually .tpl just for consistency) we’ll call this file template.tpl

<title>{TITLE}</title>
<body>
{NAVIGATION}
{CONTENT}
</body>

Copy this and save it as template.tpl
Incase you didn’t notice, this is not well-formed XHTML. It’s just for space-sake.

The template class (save this as template.class.php)

class template {
public $template;

public function __construct() {
// load the templates contents into a variable
$this->template['TEMPLATE'] = file_get_contents('template.tpl');

// set some default values in the construct
template::set('{TITLE}', 'Page title here');
template::set('{NAVIGATION}', '<a href="index.php">Home</a>');
template::set('{CONTENT}'], 'Some example content');
template::set('{STYLE}'], 'sytle.css');
}
// a function for setting template variables values
public function set($variable, $value) {
$this->template[' . $variable . '] = $value;
}

public function render() {
echo (str_replace(array_keys($this->template), array_values($this->template), $this->template['TEMPLATE']));
}
}
?>

Save this as template.class.php

Now, the index.php file (make sure all of these files are in the same folder in order for htem to work correctly)

<?php
include(’template.class.php’);
$t = new template;
// render the template
$t->render();
?>

So save that as index.php and put it in your web root directory and open it up! You should see an ugly, but working page! Let me know if you have any problems. Now, if you want to add more template variables, go right ahead! If you want to change values on conditional statements, just use the set method like this:

<?php
include(’template.class.php’);
$t = new template;
$t->set(’{TITLE}’, ‘New page title’);
$t->render();
?>