Vous êtes sur la page 1sur 99

Creating login/registration forms with php

Its 31/12/2008, happy new year everyone!. This might be the last tutorial of 2008 or the first tutorial of 2009 depending on the time this tutorial will get approved This tutorial will help you as a beginner to create a simple login page for your php projects, in this tutorial you will learn about sessions in php, inserting and retrieving records from mysql server. The database table: Before writing the code create this table in your server by running the text file attached with mysql console or simply create it yourself, we will use it to store the users information
CREATE TABLE `test`.`users` ( `id` INT NOT NULL auto_increment , `name` VARCHAR( 20 ) NOT NULL , `password` VARCHAR( 20 ) NOT NULL , `email` VARCHAR( 20 ) NOT NULL , PRIMARY KEY ( `id` ) )

Lets start:

A.The login page(main page):


In this simple php page there are three session variables we are using; logging, logged, and user they are all bool variables. We will use them to execute the right code for each scenario
<html> <head> <title>login page</title> </head> <body bgcolor="black" style="color:gray"> <form action="index.php" method=get> <h1 align="center" style="color:gray" >Welcome to this simple application</h1> <?php session_start(); if($_SESSION["logged"]) { print_secure_content(); } else { if(!$_SESSION["logging"]) { $_SESSION["logging"]=true; loginform(); } else if($_SESSION["logging"]) { $number_of_rows=checkpass(); if($number_of_rows==1) { $_SESSION[user]=$_GET[userlogin]; $_SESSION[logged]=true; print"<h1>you have loged in successfully</h1>"; print_secure_content();

} else{ print "wrong pawssword or username, please try again"; loginform(); } } }

1-the first thing to do when you are using session variables on a php page is to start the session service on the page by this line session_start();, if you ignored this line the page will work fine but the session variables wont be saved when you refresh the page or go to another page. 2-after starting the service, we check if the user is already logged in if($_SESSION['logged']), if he is we print him a nice welcome message by calling the function for the secure content (we will look at it later) 3-if he isnt logged in, we show the login fields (username and password) by the function loginform(), and set the session variable $_SESSION["logging"] to true in order to check the entered username and password when he/or she hits the login button 4-when he/or she enters the username and password then hits the login in button the code that will be only executed will be the code after else if($_SESSION["logging"]) because we have set the logging session variable to true, in this code block the variable $number_of_rows gets its value from the function checkpass() which is basically takes the username and password and checks the server if it already exists, if it exists it returns one else it will return 0..thats why we check $number_of_rows: - if it equals one if it really does we will set the variable user in the session to the entered username, and sets the logged bool variable to true. --If the $number_of_rows isnt 1, we will print him the input fields again. Now lets look at the functions: 1.loginform()
function loginform() { print "please enter your login information to proceed with our site"; print ("<table border='2'><tr><td>username</td><td><input type='text' name='userlogin' size'20'></td></tr><tr><td>password</td><td><input type='password' name='password' size'20'></td></tr></table>"); print "<input type='submit' >"; print "<h3><a href='registerform.php'>register now!</a></h3>"; }

all it does is printing out the fields to the user 2.checkpass()


function checkpass() { $servername="localhost"; $username="root"; $conn= mysql_connect($servername,$username)or die(mysql_error()); mysql_select_db("test",$conn);

$sql="select * from users where name='$_GET[userlogin]' and password='$_GET[password]'"; $result=mysql_query($sql,$conn) or die(mysql_error()); return mysql_num_rows($result); }

This function establishes a connection with the mysql server through the mysql_connect() function which takes in two parametes;1.servername (or address) 2.the username used to login to the database, if theres a password you should add it After connection to the server we choose the database that we will use using the mysql_select_db(); function which takes in 2 variables;1. The name of the database and 2.The connection variable. The sql statement:
$sql="select * from users where name='$_GET[userlogin]' and password='$_GET[password]'";

It simple gets the field that match the user login and password that the user have entered along with the ones in in the table called users, after that we run the statement using the function mysql_query($sql,$conn) and returning the results to a variable called $result Finally we return the number of retrieved rows. 3.print_secure_content()
function print_secure_content() { print("<b><h1>hi mr.$_SESSION[user]</h1>"); print "<br><h2>only a logged in user can see this</h2><br><a>href='logout.php'>Logout</a><br>"; }

No explanation needed

B. The logout page:


If the user wishes to logout, we clear the session variables this can be easily done by making him open this php page logout.php
<?php session_start(); if(session_destroy()) { print"<h2>you have logged out successfully</h2>"; print "<h3><a href='index.php'>back to main page</a></h3>"; } ?>

What we did here is starting the session and destroying it, if it was cleared successfully we display that to the user

c. Registration form:
A simple html page that lets the use enters the name and passwords and submit it to the serve on the page register.php
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>register</title> </head>

<body bgcolor="black" style="color:white;"> <FORM ACTION="register.php" METHOD=get> <h1>welcome to the registration page</h1> please input the registration details to create an account here<br> <table border="2"> <tr> <td>User Name :</td><td><input name="regname" type="text" size"20"></input></td> </tr> <tr> <td>email :</td><td><input name="regemail" type="text" size"20"></input></td> </tr> <tr> <td>password :</td><td><input name="regpass1" type="password" size"20"></input></td> </tr> <tr> <td>retype password :</td><td><input name="regpass2" type="password" size"20"></input></td> </tr> </table> <input type="submit" value="register me!"></input> </FORM> </body> </html>

Note: you can add some JavaScript to validate the code before submitting, but I didnt want to make this tutorial long and boring

d. register php page:


This php script checks the data that the user have entered in the registrationfor.php and inserts it into the database (simple, huh?).
<?php if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] ) { if($_GET["regpass1"]==$_GET["regpass2"]) { $servername="localhost"; $username="root"; $conn= mysql_connect($servername,$username)or die(mysql_error()); mysql_select_db("test",$conn); $sql="insert into users (name,email,password)values('$_GET[regname]','$_GET[regemail]','$_GET[regpass 1]')"; $result=mysql_query($sql,$conn) or die(mysql_error()); print "<h1>you have registered sucessfully</h1>"; print "<a href='index.php'>go to login page</a>"; } else print "passwords doesnt match"; } else print"invaild data"; ?>

The first line checks if all the variables in the get isnt null then it checks if the two password

fields match, if yes it connects to the server, selects the database and runs the sql insert statement, which is:
$sql="insert into users (name,email,password)values('$_GET[regname]','$_GET[regemail]','$_GET[regpass 1]')";

No explanation needed Important Notes: 1.you can use this code to check the available variables and its values in your session or any other global variables
foreach ($_SESSION as $key=>$value) { print "\$_ SESSION [\"$key\"] == $value<br>";}

2.its wise to check if a session variable exists before using it this can be done using this code:
if(isset($_SESSION['variable_name'])) print it exists; else print it doesnt;

3.you can hide the values of your form submits by using the POST method of your forms Thats all, I hope that you find this tutorial helpful and dont hesitate to ask or comment here. All the files above are attached in this thread Attached Files

registerform.php 826bytes 14457 downloads successful login.JPG 72.75K 8112 downloads logout.php 169bytes 12778 downloads register.php 730bytes 14503 downloads index.php 1.85K 16751 downloads

Edited by James.H, 26 March 2010 - 05:52

<html> <head> <title>Index</title> </head>

<body> <h2 align="center">User Registration Form</h2> <form name="forml" method="post" action="UserRegistrationFormOutput.php" enctype="multipart/form-data"> <table width="53%" border="0" align="center" cellpadding="5" cellspacing="0"> <tr> <td width="49%">Name</td> <td colspan="2"> <div align="left" <input type="text" name="name" size="25" maxlength="25"> </div> </td> </tr> <tr> <td width="49%">&nbsp;</td> <td height="2" colspan="2">&nbsp;</td> </tr> <tr> <td width="49%" height="57">Address</td> <td height="57" colspan="2"> <textarea name="address" cols="25" rows="4"> </textarea> </td> </tr> <tr> <td width="49%">&nbsp;</td> <td height="2" colspan="2">&nbsp;</td> </tr> <tr> <td width="49%"> Date of Birth</td> <td height="2" colspan="2"> <select name=birth_month> <option selected value=1>January <option value=2> February <option value=3>March <option value=4>April <option value=5>May <option value=6>June <option value=7>July <option value=8>August <option value=9>September <option value=10>October <option value=11>November <option value=12>December </select> <select name=birth_day>

<option selected value=1>01 <option value=2>02 <option value=3>03 <option value=4>04 <option value=5>05 <option value=6>06 <option value=7>07 <option value=8>08 <option value=9>09 <option value=10>10 <option value=11>11 <option value=12>12 <option value=13>13 <option value=14>14 <option value=15>15 <option value=16>16 <option value=17>17 <option value=18>18 <option value=19>19 <option value=20>20 <option value=21>21 <option value=22>22 <option value=23>23 <option value=24>24 <option value=25>25 <option value=26>26 <option value=27>27 <option value=28>28 <option value=29>29 <option value=30>30 <option value=31>31</option> </select> <input maxlength=4 name=birth_year size=4> (Year)</td> </tr> <tr> <td width="49%" height="2">&nbsp;</td> <td height="2" width="17%">&nbsp;</td> <td height="2" width="34%">&nbsp;</td> </tr> <tr> <td width="49%">Gender</td> <td height="2" width="17%"><input type="radio" name="gender" value="M">Male </td> <td height="2" width="34%"><input type="radio" name="gender" value="F">Female </td>

</tr> <tr> <td width="49%" height="5">&nbsp;</td> <td height="5" colspan="2">&nbsp;</td> </tr> <tr> <td width="49%">Music Preference </td> <td height="2" colspan="2"> <table width="100%" border="0"> <tr> <td> <input type="checkbox" name="pop" value="1"> Pop </td> <td> <input type="checkbox" name="rock" value="1"> Rock </td> </tr> <tr> <td> <input type="checkbox" name="jazz" value="1"> Jazz </td> <td> <input type="checkbox" name="metal" value="1"> Metal </td> </tr> <tr> <td> <input type="checkbox" name="instrumental" value="1"> Instrumental </td> <td>&nbsp;</td> </tr> </table> </td> </tr> <tr> <td width="49%" height="2">&nbsp;</td> <td colspan="2" height="2">&nbsp;</td> </tr> <tr> <td colspan="3"> <div align="center"> <input type="submit" name="Submit" value="Submit"> </div> </td> </tr>

</table> </form> </body> </html>

<!-- UserRegistrationFormOutput.php <html> <head> <title>Display Output </title> </head> <body> <h2> Dear <?php if ($gender=='M') { echo "Mr."; } elseif ($gender=='F') { echo "Ms."; } echo " ", $name; ?> ! You have entered the following information: </h2> <table border="1"> <tr> <td>Address </td> <td> <?php echo $address; ?> </td> </tr> <tr> <td>Date of Birth </td> <td> <?php echo $birth_month, " ", $birth_day, " ", $birth_year; ?> </td> </tr> <tr> <td colspan=2>You prefer listening to: <?php if (!(empty($pop))) { if ($pop==1){ echo " Pop "; } } if (!(empty($jazz))) { if ($jazz==1) { echo " Jazz ";

} } if (!(empty($rock))) { if ($rock==1){ echo " Rock "; } } if (!(empty($instrumental))) { if ($instrumental==1) { echo " Instrumental "; } } if (!(empty($metal))) { if ($metal==1){ echo " Metal "; } } ?> </td> </tr> </table> </body> </html> _________________ Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )

Sachith

Article subject: Re: php User Registration Form Posted: Thu Oct 20, 2011 6:36 am This part is missing in the UserRegistrationFormOutput.php file $name = $_POST['name']; $address = $_POST['address']; $birth_month= $_POST['birth_month']; $birth_day = $_POST['birth_day']; $birth_year = $_POST['birth_year']; $gender = $_POST['gender']; $pop = $_POST['pop'];

$jazz = $_POST['jazz']; $rock = $_POST['rock']; $metal = $_POST['metal']; $instrumental = $_POST['instrumental'];

msi_333

Article subject: Re: php User Registration Form Posted: Thu Oct 27, 2011 12:01 am Thanks for your modification .

Joined: Tue Mar 27, 2007 10:55 pm Posts: 2272 Location: Earth Has thanked: 39 time Have thanks: 61 time

In most of the websites and web portals to maintain the separate data for each user we are login system. By logging in to website we can maintain our details and also manage our account. Same time the website admin can find out visitor activity in the website.

Click image to view LargerSo

in order to make this, initially we have to get some details from user. The process of getting that value is called Registration. In technical terms registration is nothing but creating a unique identity for each member. In this article I will explain you how to make a simple registration form using PHP and MYSQL. You can vie demo and download the example file below Download FileDemo Create a table called registration in your database.
1 CREATE DATABASE `registration` ;

Create table in database

1 CREATE TABLE `registration`.`tbl_registration` ( 2 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , 3 `username` VARCHAR( 25 ) NOT NULL , 4 `date` VARCHAR( 20 ) NOT NULL , 5 `email` VARCHAR( 25 ) NOT NULL , 6 `password` VARCHAR( 20 ) NOT NULL , 7 `IP` VARCHAR( 20 ) NOT NULL 8 ) ENGINE = MYISAM ;

Below is the jquery script for above HTML for Ajax submit:
01 $(document).ready(function() 02 { 03 04 05 06 07 08 09 10 11 var username = $("#username").val(); var password = $("#password").val(); var email = $("#email").val(); $("#register").click(function(){ var element = $(this); var Id = element.attr("id"); var loadplacecomment = $("#message");

var mobile = $("#mobile").val(); var dataString = 'username='+ username + '&password='+ 12 password + '&email='+ email +'&mobile='+ mobile; 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 $.ajax({ type: "POST", url: "ajaxinsert.php", data: dataString, cache: false, success: function(html){ loadplacecomment.html(''); $("#message").append(html); $("#flash").hide(); } //alert(dataString); if(username==''|| password=='' || email=='' || mobile=='') { alert("Please Enter all the Fields"); } else { $("#flash").show(); $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> loading.....');

33 34 35

}); } return false;});});

Create PHP page called ajaxinsert.php


01 $username=$_POST['username']; 02 $password=$_POST['password']; 03 $mobile=$_POST['mobile']; 04 $email=$_POST['email']; 05 06 require_once("../../classes/config.php"); $query=mysql_query("INSERT INTO `webinfop_edia`.`registrationDemo` (`id`, `username`, `date`, `email`, `password`, `mobile`, `ip`) VALUES ('', 07 '$username', '".date('d-m-Y')."', '$email', '$password', '$mobile', '".$_SERVER['REMOTE_ADDR']."')"); 08 if($query) 09 { 10 echo '<div style="color:#008000; font-weight:bold;">Registred successfully..!!</div>'; 12 }else 11 13 { 14 echo '<div style="color:#c24f00; font-weight:bold;">unable to registred !!</div>';

15 }

After completing run your script. Enter all the details and give submit. When you submitting the form PHP will get values from all input fields and insert in to MYSQL database. This is the simple and easiest way of making registration form using PHP and MYSQL.

Registration Form Sample


It is simple user registration form. User Id is verified against database. If validation passed submitted data (actually User ID only) is added to the database. The sample demonstrates how VDaemon sorts out most common validation tasks. Run Registration Form Sample You can see bellow source code of two pages. First page contains form that must be validated. I call it "form page". Second page contains code for processing user input. Address of this page is specified in the "action" attribute of validated form. I call this page "action page" or "processing page".

All VDaemon-specific code is highlighted using bold font. Draw attantion to the following points: - All properly written VDaemon pages (both form and action) must begin from include('vdaemon.php'); statement. Of course you must specify a right server path to vdaemon.php file when you will write your pages. Form page must end with VDEnd(); function call. - To say VDaemon that it must check the form you need to add runat="vdaemon" attribute to the <form> tag. Form "id" or "name" attribute also must be defined and unique. - VDaemon can automatically disable all or only submit form buttons before sending data to the server to prevent visitor to submit form twice. Add disablebuttons="all" or disablebuttons="submit" attribute to the <form> tag to turn this on. - Validation rules are defined by <vlvalidator> tags. For example <vlvalidator name="UserID" type="required" control="UserID" errmsg="User ID required"> checks that visitor entered some data to the "UserID" field. And validator <vlvalidator type="format" format="email" name="Email" control="Email" errmsg="Invalid E-mail"> checks "Email" field to be a valid e-mail address. - Validator can be evaluated to true (user data is valid for this validation rule) or to false (user data is invalid). Each validator can define error message in the "errmsg" attribute. Error messages from all evaluated to false validators can be displayed in one place by summary: <vlsummary class="error" headertext="Error(s) found:" displaymode="bulletlist"> - Another way to display errors to visitor is using VDaemon labels: <vllabel errclass="error" validators="NameReq,NameRegExp" for="Name" cerrclass="controlerror">Name:</vllabel> When VDaemon parses page it replaces all <vllabel> VDaemon tags to <label> html tags. You can use any <label> attribute inside <vllabel> tag - it will be kept after replacement. VDaemon label state depends on one or several validators. Label is displayed differently in error state - it can change style and inner text. "errclass" attribute defines style for error state. "errtext" attribute defines alternative inner text. When VDaemon label is in error state it also can change style of the form input element. "for" attribute defines input element to change (you can reference input element "name" or "id" attribute). "cerrclass" attribute defines input element error class. Run Registration Form Sample

Form page source (registration_f.php)


<?php include('vdaemon.php'); ?> <html> <head> <title>Registration Form Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<link href="samples.css" rel="stylesheet" type="text/css"> </head> <body> <h1>Registration Form Sample</h1> <form id="Register" action="registration_p.php" method="POST" runat="vdaemon" disablebuttons="all"> <table cellpadding="2" cellspacing="0" border="0"> <tr> <td width="130"> <vllabel validators="UserID,UserIDExist" errclass="error" for="UserID" cerrclass="controlerror">User ID:</vllabel> </td> <td width="140"> <input name="UserID" type="text" class="control" id="UserID" size="15"> <vlvalidator name="UserID" type="required" control="UserID" errmsg="User ID required"> <vlvalidator name="UserIDExist" type="custom" control="UserID" errmsg="User ID already exist" function="UserIDCheck"> </td> <td width="300" rowspan="7" valign="top"> <vlsummary class="error" headertext="Error(s) found:" displaymode="bulletlist"> </td> </tr> <tr> <td> <vllabel errclass="error" validators="Password,PassCmp" for="Password" cerrclass="controlerror">Password:</vllabel> </td> <td> <input name="Password" type="password" class="control" id="Password" size="15"> <vlvalidator type="required" name="Password" control="Password" errmsg="Password required"> <vlvalidator name="PassCmp" type="compare" control="Password" comparecontrol="Password2" operator="e" validtype="string" errmsg="Both Password fields must be equal"> </td> </tr> <tr> <td> <vllabel validators="Password,PassCmp" errclass="error" for="Password2" cerrclass="controlerror">Confirm Password:</vllabel> </td> <td> <input name="Password2" type="PASSWORD" class="control" id="Password2" size="15"> </td> </tr> <tr> <td> <vllabel errclass="error" validators="NameReq,NameRegExp" for="Name" cerrclass="controlerror">Name:</vllabel> </td> <td>

<input name="Name" type="text" class="control" id="Name" size="15"> <vlvalidator type="required" name="NameReq" control="Name" errmsg="Name required"> <vlvalidator type="regexp" name="NameRegExp" control="Name" regexp="/^[A-Za-z'\s]*$/" errmsg="Invalid Name"> </td> </tr> <tr> <td> <vllabel errclass="error" validators="EmailReq,Email" for="Email" cerrclass="controlerror">E-mail:</vllabel> </td> <td> <input name="Email" type="TEXT" class="control" id="Email" size="15"> <vlvalidator type="required" name="EmailReq" control="Email" errmsg="E-mail required"> <vlvalidator type="format" format="email" name="Email" control="Email" errmsg="Invalid E-mail"> </td> </tr> <tr> <td colspan=2> <input name="Agreement" type="checkbox" id="Agreement" value="1"> <vllabel errclass="error" validators="Agreement" for="Agreement">I agree with the terms of service</vllabel> <vlvalidator type="required" name="Agreement" control="Agreement" errmsg="Agreement checkbox must be selected"> </td> </tr> <tr> <td colspan="2"> <input type="submit" class="control" value="Register"> <input type="reset" class="control" value="Reset"> </td> </tr> </table> </form> </body> </html> <?php VDEnd(); ?>

Action page source (registration_p.php)


<?php $sDatabase $sHostname $sPort $sUsername $sPassword $sTable = = = = = = 'db_name'; 'localhost'; 3306; 'user_name'; 'password'; 'Customers';

$rConn = mysql_connect("$sHostname:$sPort", $sUsername, $sPassword) or die(mysql_error()); mysql_select_db($sDatabase); define('VDAEMON_PARSE', false); include('vdaemon.php');

function UserIDCheck($sValue, &$oStatus) { global $sTable; $sUserID = addslashes($sValue); $oStatus->bValid = false; $oStatus->sErrMsg = "User ID '$sValue' already exist"; $sQuery = "SELECT UserID FROM $sTable WHERE UserID = '$sUserID'"; if ($rRecordset = mysql_query($sQuery)) { $oStatus->bValid = mysql_num_rows($rRecordset) == 0; mysql_free_result($rRecordset); } } // VDFormat - VDaemon function for adding or removing slashes $sUserID = VDFormat($_POST['UserID'], true); $sQuery = "INSERT INTO $sTable SET UserID = '$sUserID'"; mysql_query($sQuery); ?> <html> <head> <title>Registration Form Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="samples.css" rel="stylesheet" type="text/css"> </head> <body> <h1>Registration Form Sample</h1> <p>Your data has been written to the database</p> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td width="100">User ID:</td> <td width="300"><?php echo $_POST['UserID']; ?></td> </tr> <tr> <td>Password:</td> <td><?php echo $_POST['Password']; ?></td> </tr> <tr> <td>Name:</td> <td><?php echo $_POST['Name']; ?></td> </tr> <tr> <td>E-mail:</td> <td><?php echo $_POST['Email']; ?></td> </tr> </table> </body> </html>

PHP form tutorial in PHP Form

This tutorial takes you step by step through web form processing using PHP. You will learn how to collect input from a web form, validate and save it. This tutorial assumes that you are familiar with at least very basic PHP and HTML.

Note: You can make web forms quickly with Simfatic Forms. Simfatic Forms helps you to make complete, feature rich forms and get it online quickly. Read more here. Creating the HTML code for the form In HTML, a form is begins and ends with a <form> tag. The form tag surrounds all the inputs as well as gives instructions about how and where to submit the form. As an example, let's start creating a form in a file named myform.php. <form action="myform.php" method="post"> <!-- form fields go here --> </form> The "action" specifies what page to submit the form to. Many times, the action will be the same page as the form. The "method" indicates how the form is submitted. There are two methods: "get" and "post". Most of the time, forms will use the "post" method.( more on get and post ) Now let's add some inputs to the form. Let's add a text field that asks for your favorite movie and a submit button to submit the form. <form action="myform.php" method="post"> Which is your favorite movie? <input type="text" name="formMovie" maxlength="50"> <input type="submit" name="formSubmit" value="Submit"> </form> Getting the form data The input of type "text" is just a single line field to type in some text. We give it a name of "formMovie" which we will use later during processing. Maxlength just indicates that the browser shouldn't let the user type more than 50 characters into the text box. Congratulations! You now have a form that will submit. It doesn't do much yet, and whatever you type in "goes away" when you submit.

Let's add some PHP to process this form: <?php if($_POST['formSubmit'] == "Submit") { $varMovie = $_POST['formMovie']; } ?> <form action="myform.php" method="post"> Which is your favorite movie? <input type="text" name="formMovie" maxlength="50"> <input type="submit" name="formSubmit" value="Submit"> </form> First, remember that this form "submits to itself", meaning that the form variables will be sent to this page, and the page will load again from the top. So, the first thing we should do is to check and see if a form was submitted or not. To do that, let's look at the value of the "formSubmit" button. If its value is "Submit", then we know a form has been submitted. If not, then the user is probably visiting this page for the first time. To access this value, use the $_POST['inputname'] array, where "inputname" is the name in the HTML element. We use "$_POST" since that is the form's method. If it was "get" instead, we'd use $_GET[]. Second, after we've determined that the form was submitted, let's get the text that the user typed. Again, we use the $_POST array to get the value and put it into the $varMovie variable. Finally, we've added a "value" field to the formMovie input box, and put some PHP code in there to set the value equal to whatever the user entered. This means that if you submit the form, the text you typed in will still appear in that text box. This is very important when there are multiple inputs, as we will see later with validation. So now we have a form that still doesn't do much. Let's add another input before going into validation. <?php

if($_POST['formSubmit'] == "Submit") { $varMovie = $_POST['formMovie']; $varName = $_POST['formName']; } ?> <form action="myform.php" method="post"> Which is your favorite movie? <input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>"> What is your name? <input type="text" name="formName" maxlength="50" value="<?=$varName;?>"> <input type="submit" name="formSubmit" value="Submit"> </form> Validating the input Suppose we have a user who forgot to enter one of the fields? We need to validate the form to make sure it's complete and filled out with valid information. Note that you can use JavaScript for this, but that JavaScript can be easily turned off: always validate in the server-side script, no matter what! ( The JavaScript form validation script can help you add JavaScript validations quickly. ) Validations can be done with simple PHP if statements. Once you need to add more types of validations quickly, checkout the PHP form validation script. <?php if($_POST['formSubmit'] == "Submit") { $errorMessage = "";

if(empty($_POST['formMovie'])) { $errorMessage .= "<li>You forgot to enter a movie!</li>"; } if(empty($_POST['formName'])) { $errorMessage .= "<li>You forgot to enter a name!</li>"; } $varMovie = $_POST['formMovie']; $varName = $_POST['formName']; if(!empty($errorMessage)) { echo("<p>There was an error with your form:</p>\n"); echo("<ul>" . $errorMessage . "</ul>\n"); } } ?> In this example, the code makes some very basic checks to see that the user typed in something anythinginto both of the input fields. If the user didn't, each check will add another bullet point to the error message. Finally, when it's done making validations, it will check to see if there is an error message. If there is, it displays it. If there are no errors, it displays a success message. Note that if there are errors or not, any information that was entered into the form inputs is preserved. This way a user doesn't have to fill out the entire form again if they forgot just one thing. Saving the data to a file

Finally, let's take this data and write it into a text file. <?php if($errorMessage != "") { echo("<p>There was an error:</p>\n"); echo("<ul>" . $errorMessage . "</ul>\n"); } else { $fs = fopen("mydata.csv","a"); fwrite($fs,$varName . ", " . $varMovie . "\n"); fclose($fs); header("Location: thankyou.html"); exit; } ?> The fopen function opens up a CSV file in "a" (append) mode. This means that if mydata.csv already exists, it will point to the end of the file. If not, it will create the file and point at the start. Next, the fwritefunction takes the file pointer created by fopen and writes the name and movie separated by a comma and ending with a carriage return. Finally, the pointer to the file is closed. Now, every time a valid form is submitted, a name and movie will be written to mydata.csv. Because of the way form data is "posted" to web server, hitting the refresh button on the browser will cause the same thing to happen every time it is clicked after the form is submitted. Because of this, generally you should redirect to another page to avoid refresh button problems. Create a "thankyou.html" HTML page that says "thank you for submitting your movie" or whatever. Using PHP With HTML Forms

It is time to apply the knowledge you have obtained thus far and put it to real use. A very common application of PHP is to have an HTML form gather information from a website's visitor and then use PHP to do process that information. In this lesson we will simulate a small business's website that is implementing a very simple order form. Advertise on Tizag.com Imagine we are an art supply store that sells brushes, paint, and erasers. To gather order information from our prospective customers we will have to make a page with an HTML form to gather the customer's order. Note: This is an oversimplified example to educate you how to use PHP to process HTML form information. This example is not intended nor advised to be used on a real business website. Creating the HTML Form If you need a refresher on how to properly make an HTML form, check out the HTML Form Lesson before continuing on. We first create an HTML form that will let our customer choose what they would like to purchase. This file should be saved as "order.html" . order.html Code: <html><body> <h4>Tizag Art Supply Order Form</h4> <form> <select> <option>Paint</option> <option>Brushes</option> <option>Erasers</option> </select> Quantity: <input type="text" /> <input type="submit" /> </form> </body></html>

Display: Tizag Art Supply Order Form Quantity: Remember to review HTML Forms if you do not understand any of the above HTML code. Next we must alter our HTML form to specify the PHP page we wish to send this information to. Also, we set the method to "post". order.html Code: <html><body> <h4>Tizag Art Supply Order Form</h4> <form action="process.php" method="post"> <select name="item"> <option>Paint</option> <option>Brushes</option> <option>Erasers</option> </select> Quantity: <input name="quantity" type="text" /> <input type="submit" /> </form> </body></html> Now that our "order.html" is complete, let us continue on and create the "process.php" file which will process the HTML form information. PHP Form Processor We want to get the "item" and "quantity" inputs that we have specified in our HTML form. Using an associative array (this term is explained in the array lesson), we can get this information from the $_POST associative array. The proper way to get this information would be to create two new variables, $item and $quantity and set them equal to the values that have been "posted". The name of this file is "process.php". process.php Code:

<html><body> <?php $quantity = $_POST['quantity']; $item = $_POST['item'];

echo "You ordered ". $quantity . " " . $item . ".<br />"; echo "Thank you for ordering from Tizag Art Supplies!";

?> </body></html> As you probably noticed, the name in $_POST['name'] corresponds to the name that we specified in our HTML form. Now try uploading the "order.html" and "process.php" files to a PHP enabled server and test them out. If someone selected the item brushes and specified a quantity of 6, then the following would be displayed on "process.php": process.php Code: You ordered 6 brushes. Thank you for ordering from Tizag Art Supplies! PHP & HTML Form Review A lot of things were going on in this example. Let us step through it to be sure you understand what was going on. 1. We first created an HTML form "order.html" that had two input fields specified, "item" and "quantity". 2. We added two attributes to the form tag to point to "process.php" and set the method to "post". 3. We had "process.php" get the information that was posted by setting new variables equal to the values in the $_POST associative array. 4. We used the PHP echo function to output the customers order.

Remember, this lesson is only to teach you how to use PHP to get information from HTML forms. The example on this page should not be used for a real business. utorial Prerequisites

A web server with PHP and MySQL, or Access to a system with PHP and MySQL installed

This tutorial goes hand-in-hand with my login tutorial, so be sure to check that out! In order to create a registration page for our website, we will need the following files:

Form.html - This will contain our registration form Submit.php - This will submit the information into our database

Click here to download these files

We need to first create a table that will hold our information. To do that, run the following query in your MySQL database: MySQL Code: CREATE TABLE `members` ( `id` INT( 20 ) NOT NULL AUTO_INCREMENT , `username` VARCHAR( 20 ) CHARACTER SET cp1251 COLLATE cp1251_general_ci NOT NULL , `password` VARCHAR( 20 ) CHARACTER SET cp1251 COLLATE cp1251_general_cs NOT NULL , `firstName` VARCHAR( 20 ) CHARACTER SET cp1251 COLLATE cp1251_general_cs NOT NULL , `lastName` VARCHAR( 20 ) CHARACTER SET cp1251 COLLATE cp1251_general_cs NOT NULL , INDEX ( `id` ) , UNIQUE ( `username` ) ) ENGINE = MYISAM ;

Next, we need to create the registration form. HTML has a built in form command, and we can specify what where we are to be directed once the submit button is clicked. We can also specify names for each textbox so that we can transfer the data to our PHP file. Here is an example: HTML Code (Form.html): <html> <head>

<title>Registration Page</title> </head> <body> <h2>My Registration Page</h2> <!-- Form --> <form method="post" action="Submit.php"> First Name: <input type="text" name="firstName"> Last Name: <input type="text" name="lastName"> <br /><br /> User Name: <input type="text" name="userName"> Password: <input type="password" name="password"> <br /><br /> <input type="submit" value="Click to Register!"> </form> </body> </html>

Advertisement

That completes our HTML form, now we need to begin working on our Submit.php file. This file will do that actual processing of the data. Before we insert information into our database, we will want to make sure it is valid, for example: We don't want to insert blank data, or data with slashes. Here is the PHP code to process the data supplied by Form.html: PHP Code (Submit.php): <?php // Get the information from Form.html $fName = $_POST['firstName']; $lName = $_POST['lastName'];

$userName = $_POST['userName']; $Password = $_POST['password'];

// Echo the data echo "First Name: " . $fName . "<br />"; echo "Last Name: " . $lName . "<br />"; echo "User Name: " . $userName . "<br />"; echo "Password: " . $Password . "<br />";

// Connect to your database - Ensure you change the items in red mysql_connect('databaseURL', 'dbUserName','dbPassword'); mysql_select_db('DataBaseName') or die('Could not select database');

// Insert the data mysql_query(" INSERT INTO `members` ( `id` , `username` , `password` , `firstName` , `lastName` ) VALUES ( NULL , '$userName', '$password', '$fName', '$lastName' );") or die(mysql_error());

echo "Successfully registered!"; ?>

Advertisement:

That's all you need for this tutorial. If you have any trouble, than please feel free to send me a message now! -Prophet

Simplify Form Handling in a Big Way Jason Lengstorf on Feb 1st 2011 with 45 comments Tutorial Details

Program: PHP Difficulty: Intermediate Estimated Completion Time: 45 minutes

Download Source Files Save time, reduce maintenance pains, simplify your code, and do it all while feeling like a freakin genius! In this tutorial, learn how to use variable variables, lookup arrays, and a bit of clever programming to simplify form handling in a big way.

Variable Variables, Methods, and Properties Before we can get too deep into using a lookup array, its important to first understand the concept behind variable variables. What Are Variable Variables? Variable variable is a term, which describes the use of a variable to declare another variable. In the simplest form, a variable variable might look like: view plaincopy to clipboardprint? 1. $foo = 'A value!'; // Declare an initial value 2. $bar = 'foo'; // Wait, what's happening? 3. echo $$bar; // Holy crap! That output 'A value!' Why Should you Care? When you look at a proof of concept like the previous example, using variable variables probably looks pretty silly and overcomplicated. However, there really are solid, practical reasons to use them in some cases.

Practical Examples The responsible use of variable variables can drastically reduce the amount of code that needs to be repeated by, say, converting an associative array to an object with sanitized values. Example without variable variables view plaincopy to clipboardprint? 1. $comment = new stdClass(); // Create an object 2. 3. $comment->name = sanitize_value($array['name']); 4. $comment->email = sanitize_values($array['email']); 5. $comment->url = sanitize_values($array['url']); 6. $comment->comment_text = sanitize_values($array['comment_text']); Example with variable variables view plaincopy to clipboardprint? 1. $comment = new stdClass(); // Create a new object 2. 3. foreach( $array as $key=>$val ) 4. {

5. 6. }

$comment->$key = sanitize_values($val);

See how much simpler that was? And you can imagine what the example without variable variables would look like if the array had something like 50 or 100 values. NOTE: Im aware that you could also use array_map() and explicitly cast the array as an object to accomplish the same thing. Thats not the point. Were illustrating a concept, here. Play along.

The Problem with Form Processing Make form processing a breeze. Now that you know how to use variable variables, we can move on to the meat and potatoes of this article, which is the idea that incorporating a lookup array instead of multiple controller files or a switch statement can save you a lot of extra maintenance, repeated code, and headache in general. To illustrate our concept, were going to use the idea of form processing. This is an essential aspect of web programming, and can also be one of the most tedious areas of any project. However, after reevaluating your coding habits, you can potentially make form processing a breeze. Frequently, either an individual file is created for each form to be processed, or a switch statement is used. In this section, well go over how both solutions might be implemented, and then well examine a solution using variable variables, and how it can improve your projects. A Working Example with Multiple Form Processing Files An often used method for handling form submissions is to create a whole new file to handle each forms data separately. Take, for example, these three forms that update a user account with a new name, new email, or both: view plaincopy to clipboardprint? 1. <form action="assets/inc/ex1-form1.php" 2. 3. 4. 5. 6. method="post" id="ex1-form1"> <div> <h4>Form 1</h4> <label>Name

7. 8. 9. 10. 11.

<input type="text" name="name" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

12. </form> 13. 14. <form action="assets/inc/ex1-form2.php" 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. method="post" id="ex1-form2"> <div> <h4>Form 2</h4> <label>Email <input type="text" name="email" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

25. </form> 26. 27. <form action="assets/inc/ex1-form3.php" 28. 29. 30. 31. method="post" id="ex1-form3"> <div> <h4>Form 3</h4>

32. 33. 34. 35. 36. 37. 38. 39. 40.

<label>Name <input type="text" name="name" class="input-text" /> </label> <label>Email <input type="text" name="email" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

41. </form> Each of these forms points to a different processing file. So what does each of these files look like? Processing form 1 (assets/inc/ex1-form1.php) view plaincopy to clipboardprint? 1. <?php 2. 3. // Turn on error reporting so we can see if anything is going wrong 4. error_reporting(E_ALL); 5. ini_set('display_errors', 1); 6. 7. // Make sure our faux-token was supplied 8. if( isset($_POST['token']) && $_POST['token']==='secret token goes here' ) 9. { 10. 11. 12. // Require the necessary class require_once 'class.copterlabs_account.inc.php';

13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. }

// Create a new instance of the class $account_obj = new CopterLabs_Account();

// Handle the form submission $output = $account_obj->save_name();

// For this example, just output some data about the form submission echo "<pre>Processing File: ", $_SERVER['PHP_SELF'], "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n", '<p><a href="../../">Go back</a></p>';

24. else 25. { 26. 27. } Processing form 2 (assets/inc/ex1-form2.php) view plaincopy to clipboardprint? 1. <?php 2. 3. // Turn on error reporting so we can see if anything is going wrong 4. error_reporting(E_ALL); 5. ini_set('display_errors', 1); 6. 7. // Make sure our faux-token was supplied 8. if( isset($_POST['token']) && $_POST['token']==='secret token goes here' ) die( 'Invalid form submission' );

9. { 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. } 24. else 25. { 26. 27. } Processing form 3 (assets/inc/ex1-form3.php) view plaincopy to clipboardprint? 1. <?php 2. 3. // Turn on error reporting so we can see if anything is going wrong 4. error_reporting(E_ALL); die( 'Invalid form submission' ); // For this example, just output some data about the form submission echo "<pre>Processing File: ", $_SERVER['PHP_SELF'], "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n", '<p><a href="../../">Go back</a></p>'; // Handle the form submission $output = $account_obj->save_email(); // Create a new instance of the class $account_obj = new CopterLabs_Account(); // Require the necessary class require_once 'class.copterlabs_account.inc.php';

5. ini_set('display_errors', 1); 6. 7. // Make sure our faux-token was supplied 8. if( isset($_POST['token']) && $_POST['token']==='secret token goes here' ) 9. { 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. } 24. else 25. { 26. 27. } As you can plainly see, the example files above are duplicating a ton of code. Expand this to 15 forms on a site, and youll quickly find that maintenance could become a nightmare. The Account Class die( 'Invalid form submission' ); // For this example, just output some data about the form submission echo "<pre>Processing File: ", $_SERVER['PHP_SELF'], "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n", '<p><a href="../../">Go back</a></p>'; // Handle the form submission $output = $account_obj->save_both(); // Create a new instance of the class $account_obj = new CopterLabs_Account(); // Require the necessary class require_once 'class.copterlabs_account.inc.php';

As you can see, the processing files are creating an instance of the class CopterLabs_Account. This will be a very simple class that outputs information about a form submission. Heres the code for the class (assets/inc/class.coperlabs_account.inc.php): view plaincopy to clipboardprint? 1. <?php 2. 3. /** 4. 5. 6. 7. 8. 9. * A simple class to test form submissions * * PHP version 5 * * LICENSE: Dual licensed under the MIT or GPL licenses. *

10. * @author Jason Lengstorf <jason.lengstorf@copterlabs.com> 11. * @copyright 2011 Copter Labs 12. * @license http://www.opensource.org/licenses/mit-license.html 13. * @license http://www.gnu.org/licenses/gpl-3.0.txt 14. */ 15. class CopterLabs_Account 16. { 17. 18. 19. 20. 21. 22. public function save_name() { public $name = NULL, $email = NULL;

23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. } } } }

$this->name = htmlentities($_POST['name'], ENT_QUOTES);

return "Method: " . __METHOD__ . "\nName: " . $this->name . "\n";

public function save_email() { $this->email = htmlentities($_POST['email'], ENT_QUOTES);

return "Method: " . __METHOD__ . "\nEmail: " . $this->email . "\n";

public function save_both() { $this->name = htmlentities($_POST['name'], ENT_QUOTES); $this->email = htmlentities($_POST['email'], ENT_QUOTES);

return "Method: " . __METHOD__ . "\nName: " . $this->name . "\nEmail: " . $this->email . "\n";

You can try out this code at Example 1 on the demo page. A Working Example with a Single Processing File and a Switch Statement Another popular solution for form processing is to consolidate all the processing scripts into one file and determine what to do with the data using a switch statement.

The switch approach commonly employs a trick in which a hidden input is added to the form containing an action to be taken upon submission. This action is then used to determine what to do with the form. Here are the same three forms, from above, with actions added, all pointing to a single processing file: view plaincopy to clipboardprint? 1. <form action="assets/inc/ex2-switch.php" 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. method="post" id="ex2-form1"> <div> <h4>Form 1</h4> <label>Name <input type="text" name="name" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="action" value="update-name" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

13. </form> 14. 15. <form action="assets/inc/ex2-switch.php" 16. 17. 18. 19. 20. 21. method="post" id="ex2-form2"> <div> <h4>Form 2</h4> <label>Email <input type="text" name="email" class="input-text" />

22. 23. 24. 25. 26.

</label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="action" value="update-email" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

27. </form> 28. 29. <form action="assets/inc/ex2-switch.php" 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. method="post" id="ex2-form3"> <div> <h4>Form 3</h4> <label>Name <input type="text" name="name" class="input-text" /> </label> <label>Email <input type="text" name="email" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="action" value="update-both" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

44. </form> And the new processing file looks like: (assets/inc/ex2-switch.php) view plaincopy to clipboardprint?

1. <?php 2. 3. // Turn on error reporting so we can see if anything is going wrong 4. error_reporting(E_ALL); 5. ini_set('display_errors', 1); 6. 7. // Make sure our faux-token was supplied 8. if( isset($_POST['token']) && $_POST['token']==='secret token goes here' ) 9. { 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. // Use the new 'action' hidden input to determine what action to call switch( $action ) { // Form 1 handling case 'update-name': $output = $account_obj->save_name(); break; // Sanitize the action $action = htmlentities($_POST['action'], ENT_QUOTES); // Create a new instance of the class $account_obj = new CopterLabs_Account(); // Require the necessary class require_once 'class.copterlabs_account.inc.php';

26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. } 48. else 49. { 50. die( 'Invalid form submission' ); // For this example, just output some data about the form submission echo "<pre>Processing File: ", $_SERVER['PHP_SELF'], "\nAction: ", htmlentities($_POST['action'], ENT_QUOTES), "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n", '<p><a href="../../#ex2">Go back to example 2</a></p>'; } // If no valid action is found, something isn't right default: die( 'Unsupported action.' ); // Form 3 handling case 'update-both': $output = $account_obj->save_both(); break; // Form 2 handling case 'update-email': $output = $account_obj->save_email(); break;

51. } You can see this in action by visiting Example 2 on the demo page. This is a marked improvement over using multiple forms, but you can see that were still duplicating some code. On top of that, its a personal preference of mine to avoid switch statements whenever I can. This is due to the fact that switch uses loose comparisons ('a string' will trigger case 0 because a string evaluates to 0 if you convert it to an integer) and is extremely easy to turn into spaghetti code.

Fixing the Problem: Lookup Arrays and Variable Variables As weve seen so far, both of the above solutions have their drawbacks, and require duplicate code. Imagine if there were a dozen or more forms on the site not pretty. To address this issue, we can use a concept called a lookup array, which maps the actions passed from the form to a method called on the object. Yes, you could set the action as the method name, but that allows a bogus form submission to call any public method. Making the array a key-value pair is a small step to add a little more control without much extra work. A Working Example with a Single Processing File and a Lookup Array Using our knowledge of variable variables from the beginning of this tutorial, lets modify our demo to use a lookup array. Modify the three forms to point to a new controller file: view plaincopy to clipboardprint? 1. <form action="assets/inc/ex3-lookup-array.php" 2. 3. 4. 5. 6. 7. 8. 9. method="post" id="ex3-form1"> <div> <h4>Form 1</h4> <label>Name <input type="text" name="name" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" />

10. 11. 12.

<input type="hidden" name="action" value="update-name" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

13. </form> 14. 15. <form action="assets/inc/ex3-lookup-array.php" 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. method="post" id="ex3-form2"> <div> <h4>Form 2</h4> <label>Email <input type="text" name="email" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="action" value="update-email" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

27. </form> 28. 29. <form action="assets/inc/ex3-lookup-array.php" 30. 31. 32. 33. 34. method="post" id="ex3-form3"> <div> <h4>Form 3</h4> <label>Name

35. 36. 37. 38. 39. 40. 41. 42. 43.

<input type="text" name="name" class="input-text" /> </label> <label>Email <input type="text" name="email" class="input-text" /> </label> <input type="submit" class="input-submit" value="Submit" /> <input type="hidden" name="action" value="update-both" /> <input type="hidden" name="token" value="secret token goes here" /> </div>

44. </form> Next, put together the processing file that will handle form submissions (assets/inc/ex3-lookuparray.php): view plaincopy to clipboardprint? 1. <?php 2. 3. // Turn on error reporting so we can see if anything is going wrong 4. error_reporting(E_ALL); 5. ini_set('display_errors', 1); 6. 7. // Make sure our faux-token was supplied 8. if( isset($_POST['token']) && $_POST['token']==='secret token goes here' ) 9. { 10. 11. 12. 13. // Create a new instance of the class // Require the necessary class require_once 'class.copterlabs_account.inc.php';

14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38.

$account_obj = new CopterLabs_Account();

// Sanitize the action $action = htmlentities($_POST['action'], ENT_QUOTES);

// Set up a lookup array to match actions to method names $lookup_array = array( 'update-name' => 'save_name', 'update-email' => 'save_email', 'update-both' => 'save_both' );

// Make sure the array key exists if( array_key_exists($action, $lookup_array) ) { // Using variable variables, call the proper method and store the output $output = $account_obj->$lookup_array[$action](); } else { die( 'Unsupported action.' ); }

// For this example, just output some data about the form submission echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],

39. 40. 41. 42. } 43. else 44. { 45. 46. }

"\nAction: ", htmlentities($_POST['action'], ENT_QUOTES), "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n", '<p><a href="../../#ex3">Go back to example 3</a></p>';

die( 'Invalid form submission' );

Check this out on the demo page by trying out the forms on Example 3. Since we set the action as the key in the array, we use array_key_exists() to ensure that the action is valid. Then, we use the value that corresponds to the action as the method name. Notice that we added the parentheses after the value to make sure its executed as a method. The addition of the lookup array keeps the code concise, simple, and clear (once you get the hang of variable variables).

Summary Used responsibly, lookup arrays can make your scripts far easier to update and maintain when you combine them with variable variables. How do you think you can integrate lookup arrays and variable variables into your projects to make maintenance easier? Let me know in the comments!

Tutorials\

JavaScript & AJAX

\Rating:

1 2 3 4 5

How to Build Cross-Browser HTML5 Forms Cristian Colceriu on Jan 13th 2011 with 46 comments Tutorial Details

Technology: HTML5 Difficulty: Moderate Estimated Completion Time: 1 hour

Final Product What You'll Be Creating

Download Source Files Demo View It Online In this tutorial, were going to take a look at how to serve HTML5 forms to modern browsers, while compensating for older browsers by using a mix of Webforms2, Modernizr, jQuery UI and assorted jQuery Plugins.

Introduction HTML5 powered forms provide a great deal of semantic markup, and remove the need for a lot of JavaScript. One of the first efforts toward HTML5 was WHATWGs Web Forms 2.0, originally called XForms Basic. The spec introduced new form controls and validation, among other things. Later, it got incorporated

into HTML5, and was subsequently stripped of the repetition model, resulting in what we know today as HTML5 Forms. The ever-present issue, backward compatibility, still remains a headache though, unfortunately. Developers have to deal with the dreaded Internet Explorer, which, as you might have guessed, doesnt provide much support for the latest advancement in forms even in the latest available beta of IE9. Older versions of IE? Fagetaboutit. Nonetheless, we want to use these new features, and use them, we will! Today, were going to look at some of these new elements. Well check whether the browser support these features, and if not, provide fallbacks using CSS and JavaScript.

Tool: Modernizer Well be providing fallbacks only to browsers that dont support HTML5 forms, or certain parts of them. But instead of relying on browser sniffing, the proper technique is to use feature detection. Well use the popular Modernizr library. Modernizr is a small JavaScript library that tests the current browser against a plethora of HTML5 and CSS3 features. If you want to learn more about Modernizr, you might check out A Video Crash-Course in Modernizr premium tutorial available on the Tuts+ Marketplace.

Tool: Webforms2 Webforms2 is a JavaScript library by Weston Ruter, which provides a cross-browser implementation of the previous version of HTML5 forms, the WHATWG Web Forms 2.0 specification. Well be using it for validation and extending functionality for current elements. view plaincopy to clipboardprint? 1. <script type="text/javascript" src="webforms2/webforms2-p.js"></script>

Widget: Slider The spec describes the range input as an imprecise control for setting the elements value to a string representing a number. view plaincopy to clipboardprint?

1. <input type="range" name="slider"> Heres a preview of how it looks in Opera 10.63:

To provide fallback for other browsers, well use jQuery UIs slider widget. First, we create our initializing function, which creates the slider from the input range element. view plaincopy to clipboardprint? 1. var initSlider = function() { 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. }; }); }); } $slider.slider({ min: $input.attr('min'), max: $input.attr('max'), step: $input.attr('step'), change: function(e, ui) { $(this).val(ui.value); $input.after($slider).hide(); $('input[type=range]').each(function() { var $input = $(this); var $slider = $('<div id="' + $input.attr('id') + '" class="' + $input.attr('class') + '"></div>'); var step = $input.attr('step');

We create a new <div> element for each of our range inputs, and call the slider on that node. This is because jQuery UIs slider will not work by calling it directly on the input element. Note that were getting attributes from the input, such as min, max and step,, and are then using them as parameters for the slider. This helps our fallback slider mimic the real HTML5 slider in functionality. Next, well use Modernizr to determine if the current browser supports this input type. Modernizr adds classes to the document element (html), allowing you to target specific browser functionality in your stylesheet. It also creates a self-titled global JavaScript object which contains properties for each feature: if a browser supports it, the property will evaluate to true and if not, it will be false. With that knowledge, to detect support for input types, well use Modernizr.inputtypes*type+. view plaincopy to clipboardprint? 1. if( !Modernizr.inputtypes.range ){ 2. 3. }; If theres no support for the range input, we attach the initSlider function to jQuerys document.ready, to initialize our function after the page has loaded. This is how the slider should look in a browser without native support for the range input. $(document).ready( initSlider );

Widget: Numeric Spinner To quote Mark Pilgrim: Asking for a number is trickier than asking for an email address or web address. Thats why were provided with a separate form control which specifically deals with numbers: the numeric spinner, also called the numeric stepper. view plaincopy to clipboardprint? 1. <input type="number" value="2"> At the time of this writing, it is supported by Opera and Webkit-based browsers; heres a snapshot from Opera 10.6.

Because jQuery doesnt provide a numeric spinner, well instead use a jQuery plugin by Brant Burnett, built as a jQuery UI widget. We implement the same technique as before; build out the function to create the spinner, test with Modernizr, and attach the function to $(document).ready. view plaincopy to clipboardprint? 1. var initSpinner = function() { 2. 3. 4. 5. 6. 7. 8. 9. 10. }; 11. 12. if(!Modernizr.inputtypes.number){ 13. 14. }; Because number inputs also support min, max and step, we get the attributes from the field, and use them as parameters for initializing the numeric spinner plugin. And our fallback widget looks like so: $(document).ready(initSpinner); }); }); $('input[type=number]').each(function() { var $input = $(this); $input.spinner({ min: $input.attr('min'), max: $input.attr('max'), step: $input.attr('step')

Widget: Date Picker There are no less than six input types to serve as date pickers.

date month week time datetime and and datetime-local

At the time of this writing, the only browser that properly supports them is Opera, versions 9+. view plaincopy to clipboardprint? 1. <input type="date"> 2. <input type="month"> 3. <input type="week"> 4. <input type="time"> 5. <input type="datetime"> 6. <input type="datetime-local"> For now, well only provide fallback for the date input, using the jQuery UI Datepicker. Feel free to use any other plugin to completely mimic the functionality of the HTML5 date picker input in your implementation. view plaincopy to clipboardprint? 1. var initDatepicker = function() { 2. 3. 4. 5. 6. $('input[type=date]').each(function() { var $input = $(this); $input.datepicker({ minDate: $input.attr('min'), maxDate: $input.attr('max'),

7. 8. 9. 10. }; 11. }); });

dateFormat: 'yy-mm-dd'

12. if(!Modernizr.inputtypes.date){ 13. 14. }; $(document).ready(initDatepicker);

Widget: Color Picker Right now, no browser provides support for the color input. So, until they catch up, theyll all need to use our fallback technique. view plaincopy to clipboardprint? 1. <input type="color"> Well use Stefan Petres ColorPicker jQuery plugin, since jQuery UI does not provide one with the base pack yet. view plaincopy to clipboardprint? 1. var initColorpicker = function() {

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. }; 12.

$('input[type=color]').each(function() { var $input = $(this); $input.ColorPicker({ onSubmit: function(hsb, hex, rgb, el) { $(el).val(hex); $(el).ColorPickerHide(); } }); });

13. if(!Modernizr.inputtypes.color){ 14. 15. }; And our result: $(document).ready(initColorpicker);

Input Type: Search

The new search input type is implicitly used for semantics, but could provide a lot of interesting functionalities in the future. view plaincopy to clipboardprint? 1. <input type="search"> Currently, only Webkit-based browsers offer support for this feature. The spec also supports a results attribute to display a number of searched terms in a dropdown. It should look like this on Safari on OS X:

The rest of the browsers display this as a standard text field, so you may confidently use it with the standard markup.

Input Type : URL and Email These two input types, url and email, are used for validation purposes. They can be particularly useful in mobile browsers, where the on-screen keyboard layout can be changed to suit the focused field. This is already implemented in Safari on iOS(iPhone, iPad, iPod), and some versions of Android. view plaincopy to clipboardprint? 1. <input type="email"> 2. <input type="url"> These input types can be implemented by Webforms2 in other browsers. You can freely use these types in your new projects, as they fallback to simple textboxes. On your phone, youll find that the keyboard changes accordingly, if you supply these types to your inputs.

Attribute: Required Fields The new spec introduces the very handy required attribute. Instead of using fancy JavaScript to take care of our required fields, now we can easily use this attribute. view plaincopy to clipboardprint? 1. <input type="email" required>

For browsers that dont support this attribute, we can again use Webforms2. So, since weve included it from the start, theres nothing to worry about. Note: Be sure to assign a name attribute to your form elements, or the required attribute will not take effect.

Attribute: Pattern The pattern attribute is used for field validation and accepts values only if they match a specific format, defined with regular expressions. If the entered value does not match the pattern, the form wont submit. For example, to validate a phone number, wed have to use the following pattern, or regular expression: view plaincopy to clipboardprint? 1. <input type="text" name="Tel" pattern="^0[1-689][0-9]{8}$"> The pattern attribute can be implemented in browsers that dont support it, by using Webforms2.

Attribute: Autofocus The autofocus attribute does just what it says: automatically focuses one of our controls. It is currently supported in Webkit-based browsers(Safari, Chrome, etc.) and Opera. Remember: only one form control can receive this attribute. view plaincopy to clipboardprint? 1. <input type="email" autofocus> Webforms2 takes care of the implementation in unsupported browsers.

Attribute: Placeholder The placeholder attribute is something weve been doing with JavaScript for years. It adds a piece of information about the field, like a short description, that disappears when the field is focused. view plaincopy to clipboardprint? 1. <input name="name" placeholder="First Name"> This attribute is supported by the latest Beta Firefox and Webkit browsers.

To mimic the behavior in older browsers, well use the Placehold jQuery plugin, by Vigets Design Lab. view plaincopy to clipboardprint? 1. var initPlaceholder = function() { 2. 3. }; 4. 5. if(!Modernizr.input.placeholder){ 6. 7. }; $(document).ready(initPlaceholder); $('input[placeholder]').placehold();

Attribute: Min, Max and Step The min, max and step input attributes specify constraints for certain form controls, such as the date picker, number, and range. You can surely guess the purpose of min and max from their names. The step attribute specifies the multiple range for each click, or step. For isntance, if the step value is 2, the accepted values could be 0, 2, 4, and so on. view plaincopy to clipboardprint? 1. <input type="range" name="slider" min="0" max="20" step="5" value="0"> These attributes are only supported by Opera and Webkit browsers right now, and are implemented, as fallback for other browsers, by Webforms2.

Conclusion Weve learned today that creating forms and providing fallback for most of the new additions is a fairly easy task. If people are still trying to scare you from using HTML5 today, pay no attention to them; start using the awesome tools you have at your disposal right now! Be sure to also check out Zoltan Du Lac Hawryluks great html5Widgets, which provide similar solutions, with native JavaScript widgets.

Further Reading

28 HTML5 Features, Tips, and Techniques you Must Know HTML5 and CSS3: The Techniques youll Soon be Using /a> The Forms section of Mark Pilgrims Dive Into HTML5 Forms in HTML5 on Mozillas Developer Center The W3C HTML5 Forms Specification Working Draft Comparison of layout engines (HTML5) on Wikipedia

Tags: cross browserfallbackformshtml5jQuery ui

Enjoyed this Post? Subscribe to our RSS Feed, Follow us on Twitter or simply recommend us to friends and colleagues!

By Cristian Colceriu Rollover to read this author's bio or click through to see a full list of posts by this author. How to Create A Multi-Step Signup Form With CSS3 and jQuery written by Simone D'Amico

Nov 22, 2010 tags: css tutorials, jQuery

32 Comments

inShare

In this tutorial we will see how to create a simple multi-step signup form using CSS3 and jQuery. To spice up things a bit, we will include progress bar with the form, so the users will be able to see the percentage of form completion.

TN3 Gallery is a full fledged HTML based customizable jQuery gallery with slideshow, transitions and multiple album options. Compatible with all modern desktop and mobile browsers. Powered by jQuery. Preview You can take a look at the working demo if you click on the image below:

We will create four steps in our form: 1. username and password fields 2. first and last name and email address 3. age, gender and country 4. summary HTML Code First thing to do is to create the html structure. We need a box container with four divs, one for each step. The basic HTML code is the following: 1 <div id="container"> 2 3 4 5 <div id="first_step"> <div id="second_step"> <form action="#" method="post">

6 7 8 9

<div id="third_step"> <div id="fourth_step">

</form>

10 </div> Inside each box container we will put the fields and a simple helpfull label. You can see the code inside the first box in the code below: 1 <!-- #first_step --> 2 <div id="first_step"> 3 4 5 6 7 8 9 10 11 12 13 14 <input type="password" name="cpassword" id="cpassword" value="password" /> <label for="cpassword">If your passwords arent equal, you wont be able to continue with signup.</label> </div> <!-- clearfix --><div class="clear"></div><!-- /clearfix --> <input type="password" name="password" id="password" value="password" /> <label for="password">At least 4 characters. Use a mix of upper and lowercase for a strong password.</label> <div class="form"> <input type="text" name="username" id="username" value="username" /> <label for="username">At least 4 characters. Uppercase letters, lowercase letters and numbers only.</label> <h1>SIGN UP FOR A FREE <span>WEBEXP18</span> ACCOUNT</h1>

15

<input class="submit" type="submit" name="submit_first" id="submit_first" value="" /> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->

16 </div>

We have used three input fields: username, password and confirm password and at the end of the box, an input submit for the next step. The other boxes work in the same way.

At the end of the container box you can see a simple progress bar. This is the necessary code: 1 <div id="progress_bar"> 2 3 <div id="progress"></div> <div id="progress_text">0% Complete</div>

4 </div> The complete HTML code is the following: 1 <div id="container"> 2 <form action="#" method="post">

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <!-- #second_step --> <div id="second_step"> <input type="password" name="cpassword" id="cpassword" value="password" /> <label for="cpassword">If your passwords arent equal, you wont be able to continue with signup.</label> </div> <!-- clearfix --><div class="clear"></div><!-- /clearfix --> <input type="password" name="password" id="password" value="password" /> <label for="password">At least 4 characters. Use a mix of upper and lowercase for a strong password.</label> <div class="form"> <input type="text" name="username" id="username" value="username" /> <label for="username">At least 4 characters. Uppercase letters, lowercase letters and numbers only.</label> <!-- #first_step --> <div id="first_step"> <h1>SIGN UP FOR A FREE <span>WEBEXP18</span> ACCOUNT</h1>

<input class="submit" type="submit" name="submit_first" id="submit_first" value="" /> </div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

<h1>SIGN UP FOR A FREE <span>WEBEXP18</span> ACCOUNT</h1>

<div class="form"> <input type="text" name="firstname" id="firstname" value="first name" /> <label for="firstname">Your First Name. </label> <input type="text" name="lastname" id="lastname" value="last name" /> <label for="lastname">Your Last Name. </label> <input type="text" name="email" id="email" value="email address" /> <label for="email">Your email address. We send important administration notices to this address</label> </div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->

<input class="submit" type="submit" name="submit_second" id="submit_second" value="" /> </div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->

<!-- #third_step --> <div id="third_step"> <h1>SIGN UP FOR A FREE <span>WEBEXP18</span> ACCOUNT</h1>

<div class="form"> <select id="age" name="age"> <option> 0 - 17</option> <option>18 - 25</option>

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

<option>26 - 40</option> <option>40+</option> </select> <label for="age">Your age range. </label> <!-- clearfix --><div class="clear"></div><!-/clearfix -->

<select id="gender" name="gender"> <option>Male</option> <option>Female</option> </select> <label for="gender">Your Gender. </label> <!-- clearfix --><div class="clear"></div><!-/clearfix -->

<select id="country" name="country"> <option>United States</option> <option>United Kingdom</option> <option>Canada</option> <option>Serbia</option> <option>Italy</option> </select> <label for="country">Your country. </label> <!-- clearfix --><div class="clear"></div><!-/clearfix -->

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

</div>

<!-- clearfix --><div class="clear"></div><!-- /clearfix -->

<input class="submit" type="submit" name="submit_third" id="submit_third" value="" />

</div>

<!-- clearfix --><div class="clear"></div><!-- /clearfix -->

<!-- #fourth_step --> <div id="fourth_step"> <h1>SIGN UP FOR A FREE <span>WEBEXP18</span> ACCOUNT</h1>

<div class="form"> <h2>Summary</h2>

<table> <tr><td>Username</td><td></td></tr> <tr><td>Password</td><td></td></tr> <tr><td>Email</td><td></td></tr> <tr><td>Name</td><td></td></tr > <tr><td>Age</td><td></td></tr> <tr><td>Gender</td><td></td></tr> <tr><td>Country</td><td></td></tr> </table>

85 86 87 88 89

</div>

<!-- clearfix --><div class="clear"></div><!-- /clearfix -->

<input class="send submit" type="submit" name="submit_fourth" id="submit_fourth" value="" /> </div>

</form>

90 </div> 91 <div id="progress_bar"> 92 93 <div id="progress"></div> <div id="progress_text">0% Complete</div>

94 </div> As you can see, in the fourth step the table is empty. We fill it with the information entered by the users using jQuery. CSS Code Now we need to add the style on the form. First, we use the @fontface rule for using a custom font. Ive used the Cantarell font. The complete CSS Code is listed below: 1 /* CSS Reset (Eric Meyer) */ html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,b ig,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd ,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{border:0;outline:0;font2 size:100%;vertical-align:baseline;background:transparent;margin:0;padding:0}body{lineheight:1}ol,ul{list-style:none}blockquote,q{quotes:none}:focus{outline:0}ins{textdecoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0} 3 4 @font-face { 5 font-family: 'Cantarell';

6 src: url(../fonts/Cantarell-Regular.eot); 7 src: local('Cantarell'), url('../fonts/Cantarell-Regular.ttf') format('truetype'); 8} 9 10 body { 11 12 13 14 15 } 16 17 input[type="submit"]::-moz-focus-inner, input[type="button"]::-moz-focus-inner { border : none; } 18 input[type="submit"]:focus, input[type="button"]:focus { outline : none; } 19 20 .clear { clear: both; } 21 22 #container { 23 24 25 26 27 background: url('../images/container.png') no-repeat; width: 754px; height: 370px; margin: 20px auto; padding: 50px 0; background-color: #f9f9f9; color: #222; font-family: Cantarell, Verdana, sans-serif; font-size: 12px;

28 29 30 } 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

overflow: hidden; position: relative;

#container #first_step, #second_step, #third_step, #fourth_step { display: none; } #container #first_step { display: block; }

#container .form { margin: 66px 72px 0 72px; }

#container h1, #container h2 { font-size: Cantarell, Verdana, sans-serif; text-align: center; font-size: 24px; text-shadow: 1px 1px 2px #222; } #container h1 span { color: #a90329; }

#container h2 { color: #888; font-size: 20px; text-align: left; text-shadow: none; }

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 #container input, #container select { background: url('../images/input.png') no-repeat; color: #888; border: 1px solid #ccc; font-family: Cantarell, Verdana, sans-serif; font-weight: bold; font-size: 15px; width: 300px; height: 35px; } } #container table td:nth-child(2) { color: #a90329; } #container table td { padding: 5px 10px; #container table { margin: 20px 40px; font-size: 14px; font-weight: bold;

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 }

padding: 0 25px; margin: 20px 0; float: left;

border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px;

#container input.submit { background: url('../images/button.png') no-repeat; border: none; cursor: pointer; width: 85px; height: 38px; position: relative; bottom: 2px; left: 655px; } #container input.submit:focus { border: none; }

#container input.send{ background: url('../images/send.png') no-repeat; }

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 }

#container input.error { border: 1px solid red; } #container input.valid { border: 1px solid #1FFF00; }

#container input:focus, #container select:focus { border: 1px solid #a90329; color: #a90329; }

#container select { padding: 5px 0 5px 25px; } #container option { padding: 0 15px; }

#container label { color: #666; font-size: 12px; font-weight: bold; line-height: 14px; float: right; margin: 23px -25px; width: 270px;

115 #progress_bar {

116 117 118 119 120 121 } 122

background: url('../images/progress_bar.png') no-repeat; width: 339px; height: 24px; margin: 0 auto; position: relative;

123 #progress { 124 125 126 127 128 129 130 131 } 132 #progress_text { 133 134 135 136 position: relative; line-height: 21px; text-align: center; font-weight: bold; border-radius: 20px; -webkit-border-radius: 20px; -moz-border-radius: 20px; background: url('../images/progress.png') repeat-x; width: 0px; height: 23px;

137 138 139 140 141 142 143 }

color: white; text-shadow: 1px 1px 2px #222; width: 339px; height: 24px; top: -23px; left: 0;

jQuery Code Were going to use jQuery for: - slide the steps - check if the data are valid - change the completion percentage of progress bar

We need load jQuery library inside the page and then to use two plugins: - jQuery UI, the most famous plugin used to extend the jQuery functionality. - jQuery inputfocus, my jQuery plugin used to manage focus and blur events of the form. Our jQuery code is listed below: 1 $(function(){ 2 3 4 5 6 7 //original field values var field_values = { //id : value

'username' : 'username', 'password' : 'password', 'cpassword' : 'password',

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 };

'firstname' : 'first name', 'lastname' : 'last name', 'email' : 'email address'

//inputfocus $('input#username').inputfocus({ value: field_values['username'] }); $('input#password').inputfocus({ value: field_values['password'] }); $('input#cpassword').inputfocus({ value: field_values['cpassword'] }); $('input#lastname').inputfocus({ value: field_values['lastname'] }); $('input#firstname').inputfocus({ value: field_values['firstname'] }); $('input#email').inputfocus({ value: field_values['email'] });

//reset progress bar $('#progress').css('width','0'); $('#progress_text').html('0% Complete');

//first_step $('form').submit(function(){ return false; }); $('#submit_first').click(function(){ //remove classes $('#first_step input').removeClass('error').removeClass('valid');

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 }); if(!error) { if( $('#password').val() != $('#cpassword').val() ) { $('#first_step input[type=password]').each(function(){ $(this).removeClass('valid').addClass('error'); $(this).effect("shake", { times:3 }, 50); }); } error++; } else { $(this).addClass('valid'); //ckeck if inputs aren't empty var fields = $('#first_step input[type=text], #first_step input[type=password]'); var error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<4 || value==field_values[$(this).attr('id')] ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50);

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields = $('#second_step input[type=text]'); var error = 0; fields.each(function(){ $('#submit_second').click(function(){ //remove classes $('#second_step input').removeClass('error').removeClass('valid'); }); } } else return false; //slide steps $('#first_step').slideUp(); $('#second_step').slideDown(); return false; } else { //update progress bar $('#progress_text').html('33% Complete'); $('#progress').css('width','113px');

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 });

var value = $(this).val(); if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50);

error++; } else { $(this).addClass('valid'); }

if(!error) { //update progress bar $('#progress_text').html('66% Complete'); $('#progress').css('width','226px');

//slide steps $('#second_step').slideUp(); $('#third_step').slideDown(); } else return false;

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

});

$('#submit_third').click(function(){ //update progress bar $('#progress_text').html('100% Complete'); $('#progress').css('width','339px');

//prepare the fourth step var fields = new Array( $('#username').val(), $('#password').val(), $('#email').val(), $('#firstname').val() + ' ' + $('#lastname').val(), $('#age').val(), $('#gender').val(), $('#country').val() ); var tr = $('#fourth_step tr'); tr.each(function(){ //alert( fields[$(this).index()] ) $(this).children('td:nth-child(2)').html(fields[$(this).index()]);

116 117 118 119 120 121 122 123 124 125 126 127 128 }); }); });

});

//slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown();

$('#submit_fourth').click(function(){ //send information to server alert('Data sent');

The code from row 3 to 20 activate the inputfocus plugin to each input field. The code from row 27 to 64 check the validity of the data entered by the user (if username and password length is greather than 4 characters, if the password and confirm password fields are equal), then update the progress bar value and then slide to second step. The code from row 71 to 100 check the data integrity for the second step (if first and last name arent empty and if the email address is valid). The rest is similar to the previous code.

Conclusions and Download We have seen how simple its to create a multistep signup form. This is only an example so I omitted some features as back button, and more others. Anyway the example is ready to use and it needs only to change the form action with the link of your php file used to store data and to edit the jQuery line 125 to: $(form).unbind(submit).submit();. You can also decide to use an AJAX calls to send the informations to server, and again its very easy to implement. To see form in action click on the image below:

and if you like the final result download form files using the below button.

HTML Form Tutorial


in HTML Forms While other elements of HTML gives style and meaning to your website, an HTML form adds interactivity. HTML forms handle important functions like taking orders, surveys, user registration and more. You will hardly find a single web site without forms.

How does an HTML form work?


A web form has two parts: the HTML front end and a back end form processor. The HTML front end part handles the presentation while the back end handles the form submissions (like saving the form submissions, sending emails etc). The back end form processor script is usually written in languages like PHP, ASP or Perl.

The image below illustrates the concept:

1. 2. 3. 4. 5. 6.

A visitor visits a web page that contains a form. The web browser displays the HTML form. The visitor fills in the form and submits The browser sends the submitted form data to the web server A form processor script running on the web server processes the form data A response page is sent back to the browser.

The HTML form tag


All the input elements should be enclosed within the opening and closing <form> tags like this:
<form>

The input elements go here.


</form>

The following are the attributes of the form tag: action=Link to the form processor script The action attribute points to the server side script (the back end) that handles the form submission. Usually, this will be a script (PHP,ASP, Perl) or a CGI program. For more information, see: Switching HTML form action field dynamically method =get|post ( either GET or POST) In simple terms, if you use GET method, the form submission values are passed as part of the

URL. If it is POST, the information is sent to the server as part of the data body and will not be visible in the URL box in the users browser. If you dont specify the method, GET is taken by default. Suppose your form handler page is a Perl script named formmail.pl. the HTML form code would be:
<form action="cgi-bin/formmail.pl" method="post"> ................................ .....your input items here ..... ................................ </form>

Read more about the HTML Form tag here and about the GET and Post methods here.

The form input elements


You can have different types of input elements in a form. Examples are: check boxes, radio buttons, simple text boxes etc. Let us see how to create input elements for a form.

Single line text box

A single line text box can be used to collect the name, email, phone number etc from your web site visitors. Here is the code to create a simple text box:
<input type="text" name="FirstName" />

type=text the type attribute tells the browser that a single line text input box should be created. name=FirstName gives a name to the field. The name is used to identify the field on the server side. There are some more attributes that you can use with the text box

value=default value The text you give as value will be displayed by default in the text box. Example:
<input TYPE="text" name="FirstName" value="Your FirstName here,Please" />

maxlength=maxChars Specifies the maximum number of characters the user can enter into this text box. Let us expand our previous HTML form with some text boxes.
<form action="cgi-bin/formmail.pl" method="post"> <p> Name: <input type="text" name="FirstName" value="" size="25" maxlength="50" /> </p> <p> Email: <input type="text" name="Email" value="" size="25" maxlength="50" /> </p> </form>

There are two fields in this form for collecting the name and email address of the visitor. The <p> tags are to break the input elements in to two lines.

Submit button

After entering the data, the user presses the submit button which triggers the browser to send the data to the server. You can add a submit button to the form using the submit input type.
<input type="submit" name="submit" value="Submit" />

name =submit There can be more than one submit buttons in a form. On the server side, the submit button which was pressed can be identified using the name attribute. value=Submit The string given in the value attribute is displayed as the label of the Submit button.

Let us put it together to make a complete form page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns='http://www.w3.org/1999/xhtml'> <head > <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> <title >Form Page: sampleform</title> </head> <body> <h1>Sample form page</h1>

<form id='sampleform' method='post' action='' > <p> Name: <input type='text' name='Name' /> </p> <p> Email: <input type='text' name='Email' /> </p> <p> <input type='submit' name='Submit' value='Submit' />

</p> </form>

</body> </html>

Copy this code to an HTML file and open it in your favorite browser. See the form in action: HTML form tutorial example Next part: HTML Form Tutorial Part II : More Input El
JavaScript Form Validation : quick and easy! in HTML Forms Using client side JavaScript is an efficient way to validate the user input in web forms. When there are many fields in the form, the JavaScript validation becomes too complex. The JavaScript class presented here makes the form validations many times easier.

Contents 1. Download the JavaScript form validation script 2. Using the form validation script 3. Adding a custom validation 4. Table of Validation Descriptors 5. Showing the form validation errors next to the element 6. Conditional form validations 7. Form validation without coding! How to add JavaScript Form Validation quickly First, download the JavaScript form validation script here. The zip file contains the javascript file, examples. The script has a catalog of almost all the common validation types built-in.

The idea is to create a set of validation descriptors associated with each element in a form. The validation descriptor is nothing but a string specifying the type of validation to be performed. Each field in the form can have zero one or more validations. For example, you can have an input field that should not be empty, should be less than 25 chars and should be alpha-numeric. In other words, in order to validate a field, you just associate a set of validation descriptors for each input field in the form. Just Choose Validations!

Simfatic Forms is a feature-rich web form maker. You just have to choose the validations. More info & downloads Using the form validation script 1. Include gen_validatorv4.js in your html file just before closing the HEAD tag <script src="gen_validatorv4.js" type="text/javascript"></script> </head> 2. Just after defining your form, create a Validator() object passing the name of the form <form id='myform' action=""> <!----Your input fields go here --> </form>

<script type="text/javascript"> var frmvalidator = new Validator("myform"); //where myform is the name/id of your form 3. Now, add the validations required

frmvalidator.addValidation("FirstName","req","Please enter your First Name"); The format of the addValidation() function is: frmvalidator.addValidation(Field Name, Validation Descriptor, Error String); See below for the complete list of validation descriptors. The third parameter ( Error string ) is optional. You can add any number of validations to a field. frmvalidator.addValidation("FirstName","req","Please enter your First Name"); frmvalidator.addValidation("FirstName","maxlen=40", "Max length for FirstName is 40"); Example Here is a complete example: <form action="" id="myform" > <p> <label for='FirstName'>First Name:</label> <input type="text" id="FirstName" name="FirstName" /> </p> <p> <label for='LastName'>Last Name:</label> <input type="text" id="LastName" name="LastName" /> </p> <p> <label for='EMail'>EMail:</label> <input type="text" id="EMail" name="EMail" /> </p> <p> <label for='Phone'>Phone:</label>

<input type="text" id="Phone" name="Phone" /> </p> <p> <label for='Address'>Address:</label> <textarea cols="20" rows="5" id="Address" name="Address"></textarea> </p> <p> <label for='Country'>Country:</label> <select id="Country" name="Country"> <option value="000" selected="selected">[choose yours]</option> <option value="008">Albania</option> <option value="012">Algeria</option> <option value="016">American Samoa</option> <option value="020">Andorra</option> <option value="024">Angola</option> <option value="660">Anguilla</option> <option value="010">Antarctica</option> <option value="028">Antigua And Barbuda</option> <option value="032">Argentina</option> <option value="051">Armenia</option> <option value="533">Aruba</option> </select> </p> <p> <input type="submit" name="submit" value="Submit">

</p> </form> <script type="text/javascript"> var frmvalidator = new Validator("myform"); frmvalidator.addValidation("FirstName","req","Please enter your First Name"); frmvalidator.addValidation("FirstName","maxlen=20", "Max length for FirstName is 20");

frmvalidator.addValidation("LastName","req"); frmvalidator.addValidation("LastName","maxlen=20");

frmvalidator.addValidation("Email","maxlen=50"); frmvalidator.addValidation("Email","req"); frmvalidator.addValidation("Email","email");

frmvalidator.addValidation("Phone","maxlen=50"); frmvalidator.addValidation("Phone","numeric");

frmvalidator.addValidation("Address","maxlen=50"); frmvalidator.addValidation("Country","dontselect=000"); </script> Some Additional Notes

The form validators should be created only after defining the HTML form (only after the </form> tag. ) Your form should have a distinguished name. If there are more than one form in the same page, you can add validators for each of them. The names of the forms and the validators should not clash.

You cant use the javascript onsubmit event of the form if it you are using this validator script. It is because the validator script automatically overrides the onsubmit event. If you want to add a custom validation, see the section below

Adding a custom validation If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps: 1. Create a javascript function which returns true or false depending on the validation function DoCustomValidation() { var frm = document.forms["myform"]; if(frm.pwd1.value != frm.pwd2.value) { sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1); return false; } else { return true; } } sfm_show_error_msg() function displays the error message in your chosen style. The first parameter is the error message and the second parameter is the input object. 2. Associate the validation function with the validator object. frmvalidator.setAddnlValidationFunction("DoCustomValidation"); The custom validation function will be called automatically after other validations. If you want to do more than one custom validations, you can do all those validations in the same function.

function DoCustomValidation() { var frm = document.forms["myform"]; if(false == DoMyValidationOne()) { sfm_show_error_msg('Validation One Failed!'); return false; } else if(false == DoMyValidationTwo()) { sfm_show_error_msg('Validation Two Failed!'); return false; } else { return true; } } where DoMyValidationOne() and DoMyValidationTwo() are custom functions for validation. Clear All Validations In some dynamically programmed pages, it may be required to change the validations in the form at run time. For such cases, a function is included which clears all validations in the validator object. frmvalidator.clearAllValidations(); This function call clears all validations you set. Set focus on validation failure

By default, if there is a validation error, the focus is set on the input element having the error. You can disable this behavior by calling: frmvalidator.EnableFocusOnError(false); Table of Validation Descriptors Validation Descriptor Usage The field should not be empty. required or req Note that this validation if for fields like Textbox and multi-line text box. For selections like drop down and radio group, use an appropriate validation like dontselect or selone_radio. Limits the length of the input. For example, if the maximum size permitted is 25, give the validation descriptor as maxlen=25 Checks the length of the entered string to the required minimum. Example minlen=5 The input can contain alphabetic or numeric characters only. (Note that space or punctuation also are not allowed since those characters are not alpha numeric)

maxlen=??? or maxlength=??? minlen=??? or minlength=??? alphanumeric or alnum

alphanumeric_space Allows only alphabetic, numeric and space characters alnum_s num numeric alpha alphabetic alpha_s alphabetic_space Allow numbers only

Allow only alphabetic characters.

Allows alphabetic and space characters Validates the field to be a proper email address. (Note, However that the validation cant check whether the email address exists or not) Verify the data to be less than the value passed. Valid only for numeric fields.

email

lt=??? lessthan=???

Validation Descriptor

Usage Example: if the value should be less than 1000 give validation description as lt=1000 Verify the data to be greater than the value passed. Valid only for numeric fields. Example: if the value should be greater than 10 give validation description as gt=10 Match the input with a regular expression. Example: regexp=^*A-Za-z+,1,20-$ allow up to 20 alphabetic characters. This validation descriptor is valid only for drop down lists. The drop down select list boxes usually will have one item saying Select One (and that item will be selected by default). The user should select an option other than this Select One item. If the value of this default option is 000, the validation description should be dontselect=000

gt=??? greaterthan=???

regexp=???

dontselect=??

dontselectchk=??

This validation descriptor is only for check boxes. The user should not select the given check box. Provide the value of the check box instead of ?? For example, dontselectchk=on This validation descriptor is only for check boxes. The user should select the given check box. Provide the value of the check box instead of ?? For example, shouldselchk=on One of the radio buttons should be selected. Example: chktestValidator.addValidation("Options","selone");

shouldselchk=??

selone_radio

Compare two input elements eqelmnt=??? Compare two input elements. For example: password and confirm password. Replace ??? with the name of the other input element.

Validation Descriptor

Usage Example: frmvalidator.addValidation("confpassword","eqelmnt=password", "The confirmed password is not same as password"); The value should not be equal to the other input element Example:

neelmnt=???

frmvalidator.addValidation("password","neelmnt=username", "The password should not be same as username");

ltelmnt=???

The input should be less than the other input. Give the name of the other input instead of ??? The input should be less than or equal to the other input. Give the name of the other input instead of ??? The input should be greater than the other input. Give the name of the other input instead of ??? The input should be greater than or equal to the other input. Give the name of the other input instead of ???

leelmnt=???

gtelmnt=???

geelmnt=???

Go to the second part of this post to learn about the advanced features of this validation script.

Vous aimerez peut-être aussi