Sunday, September 30, 2007

An intro to using the GD image library with PHP

Before we really get into things, let me clue you into something. I am not a graphic designer. I have no urge to be and have no talent to be. To put it bluntly, my graphics suck. Also, to use what you learn in this tutorial, you
will need PHP 4.0.6 or higher and atleast GD 2.0.1.

Ok, with that out of the way, on to the GD library! So, what use are the GD library functions in PHP? Creating images on the fly. Why would you want to do that? Well, if there are some images that have content that changes. Take for instance this clock :






If I didn't create that clock on the fly, it would be quite a pain to show the proper time. Can you imagine having 43,200 different images on your server just to be able to show what time it is? That's why we need to create the image on the fly. Creating images on the fly isn't for everything. If you have an image that doesn't change, don't recreate it everytime. That is just putting unnecessary cycles on your server.

Getting to know the functions
OK, let's take a look at some of the functions we will be using in order to create the clock.



int ImageCreate(int x_size, int y_size)



This one is simple enough, all we need to do is pass this function two integers that represent the width and height of the image we are creating. This function returns an identifier to our blank image. Worth noting is that the upper left corner of an image is the coordinate 0,0. That means if you create an image with a width of 100, the x coordinates will run from 0 through 99.



int ImageDestroy (int im)



With ImageDestroy, we can get rid of the images we create with ImageCreate.



int ImageColorAllocate(int im, int red, int green, int blue)



The first parameter to this function is the image identifier that we will have assigned by the ImageCreate funtion. Remember good old RGB colors? I hope so, you need to use them here. The next three parameters are the values for red, green and blue respectively. Some common colors are (0,0,0) for black, (255,255,255) for white and (255,0,0) for red. Here's a link to a good RGB chart that I found. If for some reason the function fails to allocate the color, it will return a value of -1.



int ImageFilledRectangle (int im, int x1, int y1, int x2, int y2, int col)



This function is used to create a simple filled rectangle or square. All you do is pass it the image you are working with, upper left x-y coordinates, the lower right x-y coordinates and a color that you created with ImageColorAllocate. Remember that images start at 0,0!




More functions



int ImageFilledEllipse (resource im, int cx, int cy, int w, int h, int col)



With ImageFilledEllipse, we can create filled ellipses, or ovals and circles. We pass it the pointer to the image we are working on, a center point designated by cx and cy, its width and height and a color we have created.



int ImageFilledArc (int im, int cx, int cy, int w, int h,
int s, int e, int col, int style)



This function is a bit more complicated, but still not hard to use at all. Just think of it as cutting a piece of pie or cake. You pass it the image you are working on, a center point (think the middle of the pie) represented by cx and cy, its width and height, its start and end points in degrees (we'll touch on this in a second), a color you have created and its style (we'll also touch on this).

To visualize the start and end points, let's think of our pie again. Let's say we are really hungry and want to cut ourselves a piece of pie that is 1/4 of the entire pie. We would pass the function a start point of 0 degrees and an end point of 90 degrees. There are 360 degrees in a circle, so a total on 90 degrees would be one fourth of it. You can vary the start and end degrees to decide "where" your piece of the pie comes from.

With the style of the arc you can do some pretty cool stuff. There are four styles: IMG_ARC_PIE IMG_ARC_CHORD IMG_ARC_NOFILL IMG_ARC_EDGED. Using IMG_ARC_PIE is going to give you your traditional pie piece. The IMG_ARC_CHORD style produces a flat outer edge, rather than the traditional pie piece shape. With IMG_ARC_CHORD, you can make things like hexagons and other flat sided designs just by filling a circle with them. IMG_ARC_NOFILL tells the function not to fill the arc and IMG_ARC_EDGED tells it to connect up all the lines and have a border. If you need to use more than one of these, use the OR bitwise operator. I.e., IMG_ARC_CHORD | IMG_ARC_NOFILL.




And even more functions



int ImageColorTransparent (int im [, int col])



With this function, we can set the transparency color of an image or find out what the current transparency color is. If all we pass this function is a pointer to an image, we will be returned the identifier of the current transparency color. If we pass it a image identifier and a color, that color will be set to transparent for the image.



array ImageTTFText (int im, int size, int angle, int x, int y, int col, string fontfile, string text)



Ok, so we can draw all these boxes and circles and things, but how do we put text in our image? ImageTTFText is one of the ways to do so. It's actually pretty simple, but can take a little experimenting to get your text positioned right where you want it. You pass this function a image identifier, the size of the font, the angle (standard left to right reading would be an angle of 0, 90 degrees would result in text going from bottom to top.), a starting point signified by x and y, a color, the font to use and the string to display.

Of special note here is that the starting point for this function is at the lower left corner of the text, NOT the upper left. Be careful of that or your text will not be where you want it. Also, you need to provide the path to the font you want to use, here's a link to the arial font that I use in this tutorial.



int ImagePNG (int im [, string filename])



This is the function that we will use to actually display this image. All the other functions up until this point have just been manipulating the image in memory. This one will send the binary stream out so that we can see it. We could specify a filename to write the image to, but we aren't going to do that here.


Putting it all together
Ok, now let's put all those functions together and create that clock! First we need to get a few variables set so that we have the proper time and all that. Here's a bit of code to do that, how we got this code is beyond the scope of this tutorial.



= strftime("%I:%M:%S", time());
$timearray = explode(':',$time);
$hour = (((int)$timearray[0]) * 60) + (int)$timearray[1];
$minute = (int)$timearray[1];
$second = (int)$timearray[2];
if(
$hour != 0) {
$hourdegree = ((360 / (720 / $hour)) - 90) % 360;
if(
$hourdegree < 0) { $hourdegree = 360 + $hourdegree; }
} else {
$hourdegree = 270;
}
if(
$minute != 0) {
$minutedegree = ((360 / (60 / $minute)) - 90) % 360;
if(
$minutedegree < 0) { $minutedegree = 360 + $minutedegree; }
} else {
$minutedegree = 270;
}
if(
$second != 0) {
$seconddegree = ((360 / (60 / $second)) - 90) % 360;
if(
$seconddegree < 0) { $seconddegree = 360 + $seconddegree; }
} else {
$seconddegree = 270;
}
?>



Ok, there might be a more efficient way to get the degrees that we need, but this is the way I decided to do it. Anyway, on with making the image. Let's throw all those functions we saw earlier together and get an image created.



= imagecreate(100,100);
$maroon = ImageColorAllocate($image,123,9,60);
$white = ImageColorAllocate($image,255,255,255);
$black = ImageColorAllocate($image,0,0,0);

ImageFilledRectangle($image,0,0,99,99,$white);
ImageFilledEllipse($image,49,49,100,100,$black);
ImageFilledEllipse($image,49,49,95,95,$maroon);
ImageFilledEllipse($image,49,49,75,75,$white);
ImageFilledEllipse($image,49,49,5,5,$maroon);
ImageFilledArc($image,49,49,50,50,$hourdegree-4,$hourdegree+4,$maroon,IMG_ARC_PIE);
ImageFilledArc($image,49,49,65,65,$minutedegree-3,$minutedegree+3,$maroon,IMG_ARC_PIE);
ImageFilledArc($image,49,49,70,70,$seconddegree-2,$seconddegree+2,$black,IMG_ARC_PIE);

ImageColorTransparent($image,$white);

ImageTTFText ($image, 8, 0, 44, 11, $white,"/home/mjw21/www/images/arial.ttf","12");
ImageTTFText ($image, 8, 0, 89, 53, $white,"/home/mjw21/www/images/arial.ttf","3");
ImageTTFText ($image, 8, 0, 47, 96, $white,"/home/mjw21/www/images/arial.ttf","6");
ImageTTFText ($image, 8, 0, 5, 53,$white,"/home/mjw21/www/images/arial.ttf","9");

imagePNG($image);
imagedestroy($image);
?>



Let's finish it up
Ok, so we have it all together and have an image created. Now if you just try and stick that code in your page, it will not display correctly. The reason for this is that the browser doesn't know how to interpret the data that is coming at it. Some people solve this by writing the image to a temporary file; I don't like that method. If you write to a temporary file then you have to go back and clean those up. What a hassle. What I do is put all the code into its own PHP file and add a header to it. Then just act as if the PHP file was an image file and use standard HTML to include it.

So, here is our finished clock all ready to go into its own PHP file :



("Content-type: image/png");
$time = strftime("%I:%M:%S", time());
$timearray = explode(':',$time);
$hour = (((int)$timearray[0]) * 60) + (int)$timearray[1];
$minute = (int)$timearray[1];
$second = (int)$timearray[2];
if(
$hour != 0) {
$hourdegree = ((360 / (720 / $hour)) - 90) % 360;
if(
$hourdegree < 0) { $hourdegree = 360 + $hourdegree; }
} else {
$hourdegree = 270;
}
if(
$minute != 0) {
$minutedegree = ((360 / (60 / $minute)) - 90) % 360;
if(
$minutedegree < 0) { $minutedegree = 360 + $minutedegree; }
} else {
$minutedegree = 270;
}
if(
$second != 0) {
$seconddegree = ((360 / (60 / $second)) - 90) % 360;
if(
$seconddegree < 0) { $seconddegree = 360 + $seconddegree; }
} else {
$seconddegree = 270;
}

$image = imagecreate(100,100);
$maroon = ImageColorAllocate($image,123,9,60);
$white = ImageColorAllocate($image,255,255,255);
$black = ImageColorAllocate($image,0,0,0);

ImageFilledRectangle($image,0,0,99,99,$white);
ImageFilledEllipse($image,49,49,100,100,$black);
ImageFilledEllipse($image,49,49,95,95,$maroon);
ImageFilledEllipse($image,49,49,75,75,$white);
ImageFilledEllipse($image,49,49,5,5,$maroon);
ImageFilledArc($image,49,49,50,50,$hourdegree-4,$hourdegree+4,$maroon,IMG_ARC_PIE);
ImageFilledArc($image,49,49,65,65,$minutedegree-3,$minutedegree+3,$maroon,IMG_ARC_PIE);
ImageFilledArc($image,49,49,70,70,$seconddegree-2,$seconddegree+2,$black,IMG_ARC_PIE);

ImageColorTransparent($image,$white);

ImageTTFText ($image, 8, 0, 44, 11, $white, "/home/mjw21/www/images/arial.ttf","12");
ImageTTFText ($image, 8, 0, 89, 53, $white, "/home/mjw21/www/images/arial.ttf","3");
ImageTTFText ($image, 8, 0, 47, 96, $white, "/home/mjw21/www/images/arial.ttf","6");
ImageTTFText ($image, 8, 0, 5, 53, $white,"/home/mjw21/www/images/arial.ttf","9");

imagePNG($image);
imagedestroy($image);
?>



Simple huh? There are lots of other functions available in the GD library, so get out there and experiment with them. If you look around my site you will see that the graphics for the code ratings are also created on the fly. The possibilities are endless!

Custom Error 404 Documents with PHP

Have you ever designed your website, built the structure and decided one day that you want to completely redesign your layout? Well, if you have an established website, changing your structure can be a real pain for your users or people searching for your site in search engines. This tutorial will show you how to avoid getting those Error 404 Not Found errors and redirect people back into your new design.

Let's say that we have a few files such as this:

PHP Example: (!)

Your Site Root
/index.php
/page1.php
/page2.php
/page3.php


Your new layout schema that you decided to use will change to this:

PHP Example: (!)

Your Site Root
/index.php
/articles.php (Was page1.php)
/
images.php (Was page2.php)
/
guestbook.php (Was page3.php)


We will assume that you are going to remove the old files after you do your site design. When your site was running before you had about 10 websites linking to your pages and you had submitted everything to search engines. When people click on your old links, they'll get an Error 404 / Document Not Found error message. Let's avoid getting that message and direct the users to your index to avoid any traffic loss.

Utilizing Apache's built in custom error document handling you can setup your own error 404 document that redirects the user to your index page and gives them a message as well as displays your index page. The first thing we need to do is build our error handler. I use a php script that includes my index.php file, gives the user a message at the top and the re-directs them to the main page after 2 seconds. Here's how:

PHP Example: (!)
php

//errror404.php



echo "#FFFF00" size="3">
You have reached a page that has changed or no longer exists.

You have been redirected to our index page. Please update your bookmarks!strong>center>font>";



//Meta refresh to send them back to index.php


echo "<meta http-equiv="refresh" content="2;URL=/index.php">";


//include the index.php so that we can give them something to look at besides an ugly error

include 'index.php';


?>

There you have it! A simple php script that gives you a good looking Error 404 page and redirects the user to your index page. On the \
next\(array array_arg\)\

Move array argument\'s internal pointer to the next element and return it', CAPTION, 'next');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.next.html">next
page, we'll show you how to setup a htaccess \
file\(string filename \[, int flags\[, resource context\]\]\)\

Read entire file into an array', CAPTION, 'file');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.file.html">file
that allows Apache to use this new error404.php script.

The \
next\(array array_arg\)\

Move array argument\'s internal pointer to the next element and return it', CAPTION, 'next');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.next.html">next
step requires you to either have administrative access to your Apache web server's configuration files or send an email to your admin and ask them to allow overrides for your website. A directive should be added to your httpd.conf for the directory which your website lives in. Let's say for this example it's /www/htdocs. Here's a line in your httpd.conf that you must have for this .htaccess \
file\(string filename \[, int flags\[, resource context\]\]\)\

Read entire file into an array', CAPTION, 'file');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.file.html">file
to work:

PHP Example: (!)
<Directory /www/htdocs/yoursite>
AllowOverride FileInfo
Directory>


Once you have that done, you'll need to create a \
file\(string filename \[, int flags\[, resource context\]\]\)\

Read entire file into an array', CAPTION, 'file');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.file.html">file
called ".htaccess" and place it inside your website's directory. Here's how simple this .htaccess \
file\(string filename \[, int flags\[, resource context\]\]\)\

Read entire file into an array', CAPTION, 'file');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.file.html">file
is:

PHP Example: (!)
ErrorDocument 404 /error404.php


Wow that was simple eh? After you have completed all of the above steps, you can now test it out. Let's call up http://www.yourdomain.com/foo.php (Where foo.php is a \
file\(string filename \[, int flags\[, resource context\]\]\)\

Read entire file into an array', CAPTION, 'file');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.file.html">file
that does not exist). You should be directed to your index page and see a message that appears at the top of the screen for approximately 2 seconds and then the user will be directed back to your index.php file.

Congratulations, You've successfully redirected all broken links on your website back to your index! You will no longer lose traffic due to random clean-ups of your files and site changes. Just don't delete the error404.php because that would be too ironic that you can't even display your own error document!

Here's a few more custom error documents that you can make for your website. Just use the same methods above that we used for creating these new pages. If you were really cool, you could setup a switch inside your error404.php \
file\(string filename \[, int flags\[, resource context\]\]\)\

Read entire file into an array', CAPTION, 'file');" onmouseout="return nd();" href="http://www.phpfreaks.com/phpmanual/page/function.file.html">file
and manage all of your custom errors in one file. Here's the list:

Error in Client

400 Bad syntax
401 Unauthorized
402 Not Used (Payment Granted)
403 Forbidden
404 Not Found

Error in Server

500 Internal Error
501 Not Implemented
502 Overloaded
503 Gateway Timeout

More information can be found at the Apache Webserver page: http://httpd.apache.org/docs/custom-error.html

Using output from other sites in your PHP scripts

Intended audience

This tutorial is intended for the PHP programmers who wish to use the output from other Web sites in their own scripts. A moderate understanding of PHP and HTML is assumed.

Overview

The example used in this tutorial is the automatic translation of phrases to multiple languages, to aid the development of multilingual applications.

When developing for the Internet, your audience will more than likely be from a variety of different countries and may not speak your language. You can easily adapt your own scripts to support multiple languages without speaking any of those languages yourself.

translate.dictionary.com is one of many Web sites offering translation services, and can be used within your own PHP scripts. Although the translations may not be perfect, they demonstrate the ability of your application to support multiple languages.

Objectives

In this tutorial you will learn how to:

  • Read the output from third-party Web sites in your own scripts
  • Send the correct information to Web sites to generate useful data
  • Identify the output format and decide how to extract the data you require
  • Utilize the data you have collected

Definitions

Target Web Page: The Web page from which data will be collected.

Background Information

This tutorial relies on the output from an external Web site. If and when the output from that site changes, modifications to any scripts that read information from the site may be required. If you are willing to spend a little time investigating how interactive Web sites work, the data they require and what they produce, you will often find that these sites produce useful data that you can use to enhance your own scripts.

Prerequisites

You may find it helpful to read the following sections of the PHP documentation:

  • Filesystem functions
  • Regular Expression Functions

How it works

First of all, visit the Web site http://translate.dictionary.com , where you will see the following form:

You need to find the data that this form collects to perform a translation. This particular page has a simple form and it is easy to pick out the elements you require. They are:

Your Target Web Page will therefore be http://translator.dictionary.com/fcgi/translate

To translate plain text, type or paste here:


Next you define a variable called 'text' which will contain your phrase:

Now you define a variable called 'lp' which will contain one of the values above.

You now have the information required to begin translating phrases for your own applications. The two variables $text and $lp must be supplied to http://translator.dictionary.com/fcgi/translate. This will generate a result that you can use in your own scripts.

Type a phrase into the text area and submit the form manually, the source of the resulting page contains:

tener diversión con PHP<-The translation of your phrase

The information returned can be examined and the translation extracted.

Sending the information to dictionary.com and reading the results

It's time to generate your first translation.

Code Flow

  • Send the correct information to dictionary.com and read the results
  • Check for the presence of your translation in the correct format
  • Return the translation or an error if something went wrong
PHP
function translate($phrase, $type){
$fp = @fopen("http://translator.dictionary.com/fcgi/translate?lp=$type&text=".urlencode($phrase), "r");
if(
$fp){
while(
$in = fread($fp, 1024))
$reply .= $in;
fclose($fp);
if(
ereg("(.*)", $reply, $reg))
return
trim($reg[1]);
else
return
"Error : Could not find translation!";
}
return
"Error : Could not connect to translate.dictionary.com!";
}

// translate a phrase from english to german
echo "First translation = ".translate("Having fun with PHP", "en_ge")."
\n"
;
?>


The output from the script is -> First translation = Spa? mit PHP haben

Now that you have the ability to translate phrases to multiple languages, you can store your translations in a database for use with your PHP scripts!

Using Perl Compatible Regular Expressions with PHP

Intended Audience

This tutorial is intended for the PHP programmer interested in using Perl Compatible Regular Expressions (or PCRE for short) to match or replace values within its target.

A basic understanding of PHP and an overview of Perl will be given in this tutorial. Knowledge of the intended use of regular expressions will be helpful, although this tutorial should make that clear.

Readers interested in learning more about Regular Expressions and PHP before reading this tutorial are encouraged to do so by referring to:

Zend.com's PHP manual entry on PCRE
http://www.zend.com/manual/ref.pcre.php

Zend.com's PHP manual entry on preg_* functions
http://www.zend.com/manual/function.preg-replace.php

Overview

This tutorial will show you how to replace, match and otherwise manipulate strings within a target by using regular expressions. A regular expression is used for complex string manipulation in PHP and can be very handy when one needs to validate a value, grab information from an outside source, locate information within a page, or replace all of one specified string or value with another. It can be a great timesaver by doing all of the "find and replace" work that one would otherwise have to do by hand. Regular Expressions can also take care of much of the double checking that one often does when, for example, making sure that e-mail address submitted to a listserv are correct, or that URLs submitted for links are in the proper format.

Learning Objectives

In this tutorial, you will learn how to use the following PHP functions:

preg_replace()
preg_match()
preg_match_all()
preg_replace_all()

Definitions

Regular Expression: A function consisting of an expression used for complex string manipulation in PHP.

PCRE: Perl Compatible Regular Expressions - use syntax widely used in Perl. Alternate Regular expressions can employ POSIX-extended syntax.

Target: The text file, web page, or other file that will be "searched" by the regular expression.

Object: The entity within the target that will be searched for.

Background Information

When using regular expressions, there is one thing more important than all the rest. That item is syntax. Without the proper syntax, and by which the exact definition of what you are searching for is set, the regular expression can function improperly without limitation or, it can simply not function at all. In order to alleviate constant syntax problems, a plan of attack and a bit of patience is usually the key. So, it is usually prudent with a regular expression, especially depending on the restrictions on has in place, to first over specify the target and then simplify down. This amount of scrutiny insures that the object you are searching for is the only one grabbed, instead of outputting large amounts of unnecessary and unwanted matches.

Prerequisites

As a prerequisite to understanding the Perl Compatible Regular Expressions, it is recommended that you review:


The links outlined above in the Intended Audience section


Become familiar and constantly refer to the Pattern Syntax section of the Zend manual when constructing future regular expressions:

http://www.zend.com/manual/reference.pcre.pattern.syntax.php

PCRE Syntax

The types of regular expressions that will be covered in this tutorial are called Perl Compatible Regular Expressions, or PCRE for short. What this means is that the regular expressions associated with these PHP functions closely follow the syntax used in Perl regular expressions. This syntax is primarily used with the PREG functions in PHP, i.e. preg_replace, preg_match, preg_quote, preg_split, preg_grep, etc. These functions tend to be slightly faster than their POSIX compatible relatives (eregi, ereg, ereg_replace, etc). The syntax used can be confusing, but insures a very specific set of search criteria. The best place to find a large portion of this syntax is in the PHP manual:
http://www.zend.com/manual/reference.pcre.pattern.syntax.php

The first type of syntax to cover involves meta-characters. These characters are stand in values that cause the expression to behave in a certain way. They come in most handy because regular expressions are used to find certain patterns represented by the object you are searching for within a target. For example, if you were searching for an e-mail address in a Web page, you would look for the combination of an @ symbol followed by a period and then a predictable array of endings, i.e. com, org, net, etc. A complete list of these meta-characters can be found at the aforementioned link, a few of the most important ones will be illustrated here.

/ indicates a delimiter (used in pattern modifiers or to begin/end an
expression)
^ indicates the start of the target string to match
$ indicates the end of the target string to match

\ is used as a general escape character
{ } encloses a minimum, maximum value - used to indicate number of characters in a matching string
( ) encloses a subpattern
| separates alternative patterns


So, for example:

/car/ (note the beginning and closing / for delimiters, these enclose your expression)

indicates that the regular expression is looking for the letters "car". So, if a sentence looked like such:

I own a car now.

A match would be found, and the match would return "car".
Alternatively, if we had put the word carriage into the sentence instead of car, a match would still be made, but it would only return the word "car" since that is what was requested in the regular expression.

Try it yourself:

php
preg_match
('/car/', 'I own a car now.', $output);
echo
$output[0];
?>

So, for another example:

/car.*/

indicates that the regular expression is looking for the letters "car", but looking for them with following characters. So, if a sentence looked like such:

I own a carriage now.

A match would be found, and the match would return "carriage".
Alternatively, if we had used the first sentence, a match would have been made and the words "car now" would have been returned. This is because the regular expression requested a match starting with "car" and all characters after it on that line.

Try it yourself:

php
preg_match
('/car.*/', 'I own a carriage now.', $output);
echo
$output[0];
?>

So, one more example:

/ca(r|nyon|)/

indicates that the regular expression is looking for the letters "car" AND also looking for the word "canyon". So, if a sentence looked like this:

I own a car now.

A match would be found, and the match would return "car". Alternatively, if the word car had been replaced with canyon, a match would have been made and the words "canyon" would have been returned. This is because the regular expression requested a match starting with "ca" and either "r" or "nyon" ending the match.

Try it yourself:

php
preg_match
('/ca(r|nyon|)/', 'I own a car now.', $output);
echo
$output[0];
?>

How the Scripts Work

In this tutorial, the following example is given:

E-mail Validation: uses a regular expression to make sure that an e-mail address is in fact a valid e-mail address. This can be used to validate e- mail address submitted via a form or to search a target page for e-mail addresses and to display them.

Script Overview

Having read the introduction, you should have an understanding of what regular expressions are. In the following example, the versatility of regular expressions is illustrated Remember, regular expressions are tools that can be used in a variety of ways, not just those illustrated here. They can make otherwise tedious and lengthy jobs a breeze. At the end of the tutorial, the regular expressions are matched with PHP in context to show how they would be used.

E-mail Validation

The regular expression this tutorial covers is also one of the most popular uses of regular expressions. By validating an e- mail address, one can insure that at least the format is correct (although it cannot validate if the address is authentic). This can prevent accidental submissions of partial e-mail addresses to your database or form, it can insure that an e-mail address submitted to a listserv is valid, or it can be used to search and replace all the e-mail addresses for contact on your website with a different or updated e-mail address. All of these uses can employ a regular expression that would make the job of checking e-mail addresses by hand, obsolete.


Code Flow

Assign the regular expression output to a variable ($okay).

Invoke the preg_match function in order to match the objects in the target file with the desired validation parameters.

php
$okay
= preg_match('/^[A-z0-9_\-]+\@(A-z0-9_-]+\.)+[A-z]{2,4}$/', $emailfield);
?>

Items to match:

begin with a delimiter /

then indicate the beginning of the line with ^

then, [A-Za-z0-9_\-] is any character A-Z, a-z, 0-9 and _ or - .

Then, indicate that this pattern is one or more with the + symbol.

Then, just add a [@] after the plus to look for the @ symbol in the e-mail address (a dead giveaway for validation scripts).

Now all you need is to repeat your previous criteria for matching (text between A and Z or the numbers 0 - 9)

Adding a () around the next subset at the additional [.] tells it to look for more text following the . (the .com,.net,etc)

Then adding a minimum/maximum bracket {2,4} tells it to look for an ending that falls within those values (i.e. .de, .au, etc)

Finally, the $ indicates the end of the target string

And the expression is closed with our ending delimiter /

Scripts

E-mail Validations (email.php)


php
if ($submit) {
$okay = preg_match(
'/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{2,4}$/',
$emailfield
);
if (
$okay) {
echo
"E-mail is validated";
} else {
echo
"E-mail is incorrect";
}
}else {
?>

E-mail address:



}
?>

You can see immediately, if an e-mail address is provided that does not fit our criteria, it will be returned as incorrect. However, if it does fit our specified criteria, it is validated:





Here's what happens with a non-valid e-mail address is inserted:








Conclusion


That's all there is to it. With this example, you can readily see how useful regular expressions can be. They are tools that programmers, when effectively implemented, wield with an unmatched amount of power. While PHP does over the POSIX compatible regular expressions, which generally has slightly easier syntax, the PCRE regular expressions are generally reputed to have widespread acceptance, powerful implementations and tend to be faster when used with large files or large strings.