Validating Forms and Regexes:
The web alone is stateless. With CGI programs, the web is transformed into a dynamic environment opening up a world of endless possibilities. One can ask users for data via forms, but what use would this data serve if it weren't validated first? In this article, I wish to show you the in's and out's of forms and validation in PHP, hence the name. Sure you can do this in JavaScript, but what if the user doesn't have a JavaScript capable browser or has it turned off? So doing this on the server side provides you with better data.

Let's begin by creating a form in HTML. We want to collect some basic demographics which include the user's name, e-mail address, age, and country.

<form method=post action="validate.php">
Name: <input type=text name=name><br>
E-mail: <input type=text name=email><br>
Age: <input type=text name=age size=2><br>
Country: <select name=country> <option value=cn>Canada
<option value=cr>Costa Rica <option value=de>Germany
<option value=uk>United Kingdom
<option value=us>United States
<select>
<p align=center>
<input type=submit value="Submit!">
</form>
Here's where PHP comes in. Variables can be used to store the information of any form. Simple assign a name to the form element and the data entered will automatically be available to your PHP script as a variable with the same name as the form element. e.g. a textbox with the name "name" will be available to your PHP script as the variable "$name". Once you have the variables you can do all sorts of things with them such as e-mailing them to you, inserting them into a database, etc. This isn't the scope of this article, however.

Let's say a malicious user visits your web site and decides to cause some trouble by submitting false data through your web form. You need some way to stop this. Yes, you can do this by using conventional if/else statements:

<?php if ($name == "") { echo "You must enter a name!"; exit; } else { // do something useful with the data here... } ?>

but chances are, you're probably going to need more power. The answer is regular expressions...
-- Continued...2
Sponsored Links: