Rabu, 07 Januari 2009

Cara Membuat Validasi Dengan PHP

Form Validation Using PHP

* Home
* RSS feed for page


* Authentication
* Getting Started
* MySQL Installation
* PHP Installation
* Validation

View more
Table of Contents

* Installing PHP and MySQL
* Getting Started with PHP
* Paging Using PHP
* Form Validation Using PHP
* Creating A Guestbook Using PHP and MySQL
* User Authentication with Image Verification
* Basic User Authentication
* Image Gallery : Add New Album
* Image Gallery : Modify & Delete Albums
* Image Gallery : Add Image
* Image Gallery : Modify & Delete Images
* Opening & Closing PHP Tags
* Using PHP Comments
* PHP Variables
* PHP Variable Types
* Strings in PHP
* PHP Control Structures
* PHP Functions
* PHP Forms
* PHP Editors
* Paging Using PHP and MySQL (Part II)
* Finding PHP and MySQL Hosting
* Uploading Files To the Server Using PHP
* User Authentication in PHP
* PHP and MySQL Resources on the Net
* Creating A Guestbook Using PHP and MySQL ( Part 2 )
* Admin Page For Content Management System (CMS)
* Image Gallery Administration Page
* Image Gallery : Image List & Detail
* Image Gallery : Album List
* Reading a Remote File Using PHP
* Read HTML files using PHP
* Remove a File Using PHP
* Remove a File Extention Using PHP
* Finding Sub-Strings using PHP
* Executing a Shell Command Using PHP
* List a Directory's Contents Using PHP
* Reading a File Using PHP
* PHP Number Formats
* Determine a File Extension Using PHP
* Append a String to a File Using PHP

Page Details
Published by:
on 12-18-2008
1 person found this article useful.

Comments (2)
100% of people found this useful
Form Validation Using PHP
Filed under: Validation [Edit Tags]

Whenever you make a form you should not leave it alone without any form validation. Why? Because there is no guarantee that the input is correct and processing incorrect input values can make your application give unpredictable result.

You can validate the form input on two places, client side and server side.

Client side form validation usually done with javascript. Client side validation makes your web application respond 'faster' while server side form validation with PHP can act as a backup just in case the user switch off javascript support on her browser. And since different browsers can behave differently there is always a possibility that the browser didn't execute the javascript code as you intended.

Some things you need to check :

* empty values
* numbers only
* input length
* email address
* strip html tags

To show form validation with php in action I'll use the contact form in this website. Click here to see the contact form and then take a look at the source code.

This contact form requires four input :

* sender name
* sender email
* message subject
* message body

First let's focus on the client side validation. On the "Send Message" button I put this javascript code : onClick="return checkForm();", which is triggered when you click on it. Clicking the button will run the function checkForm().Every input is checked to see whether they are valid input. When an invalid input is found the function returns false so the form is not submitted. When you insert valid input the function will return true and the form is submitted.

Go ahead and play around with the form. Try entering only spaces for the input value or enter glibberish string as email address.

The code snippet below shows the client part of contact form.

Example : contact.php
Source code : contact.phps

Contact Form

Your Name
Your Email


Now we'll take a better look at checkForm() function :

function checkForm()
var cname, cemail, csubject, cmessage;
cname = sname;
cemail = email;
csubject = subject;
cmessage = message;

// ... the rest of the code


In the beginning of the function I use the keyword var to declare four variables to reference the form input . They are cname, cemail, csubject and cmessage. These variables will reference the form input sname, email, subject and message respectively.

Javascript treats a document and it's element as object. The message form is named msgform so to access is we use window.document.msgform and to access the sname input text we can use window.document.msgform.sname.

To avoid the hassle of writing the window.document.msgform part whenever we want to access a form object I use the with() keyword. Without it the checkForm() function would look like :

function checkForm()
var cname, cemail, csubject, cmessage;

cname = window.document.msgform.sname;
cemail = window.document.msgform.email;
csubject = window.document.msgform.subject;
cmessage = window.document.msgform.message;

// ... the rest of the code


Next we'll validate each form input.

function checkForm()
// variable declarations goes here ...

if(trim(cname.value) == '')
alert('Please enter your name');
return false;
else if(trim(cemail.value) == '')
alert('Please enter your email');
return false;
else if(!isEmail(trim(cemail.value)))
alert('Email address is not valid');
return false;
// The rest of validation code goes here ...

To access the value of the name input box we use cname.value. The name values is trimmed to remove extra spaces from the beginning and end of the name. If you do not enter your name or only entering spaces then an alert box will pop up. Using cname.focus() the cursor will be placed to the name input box and then checkForm() return false which cancel the form submit.

The code above uses trim() function. This is not a built in javascript function. I can't understand why there is no trim() function in javascript, even VBScript has it. Anyway it's not a big deal because we can just make our own trim() function. The solution here uses regular expression to replace any spaces in the beginning and end of a string with blank string.

function trim(str)
return str.replace(/^\s+|\s+$/g,'');

The forward slash (/) is used to create a regular expression. Note that it is not a string, you don't have to use quotes and it won't work if you use quotes. Let's chop the regular expression notation so we can understand it better :

* ^ : the beginning of a string
* $ : end of string.
* \s : single whitespace character (tab also count as whitespace)
* + : one or more
* | : conditional (OR)
* g : global, mainly used for search and replace operation

So in english the search replace function above can be read as :

"Replace one or more whitespace character from the beginning or ending of a string with blank character"

As for the email input, we need to double check it. First, check if the email is entered and second check if the input is in a valid email format. For the second check well use isEmail() function. This function also uses regular expression.

A valid email format can be described as :

[ a string consisting of alphanumeric characters, underscores, dots or dash ] @ ( [ a valid domain name ] DOT [ a valid TLD ]) OR [a valid IP adress ]

In case you're wondering TLD means Top Level Domain such as com, net, org, biz, etc.

When you see the source code you will see that the regular expression in isEmail() function is actually written in one line. I have to break them into multiple lines just to fit the space. The PHP Manual explains the regular expression syntax for PHP in depth, but if you want to learn regular expression for javascript you can go to : http://www.regular-expressions.info

Finally, if all input are considered valid checkForm() returns true and the form will be submitted. This will set the $_POST['send'] variable and now we start validating the input on the server side using PHP.

$errmsg = ''; // error message
$sname = ''; // sender's name
$email = ''; // sender's email addres
$subject = ''; // message subject
$message = ''; // the message itself

$sname = $_POST['sname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

if(trim($sname) == '')
$errmsg = 'Please enter your name';
else if(trim($email) == '')
$errmsg = 'Please enter your email address';
else if(!isEmail($email))
$errmsg = 'Your email address is not valid';
else if(trim($subject) == '')
$errmsg = 'Please enter message subject';
else if(trim($message) == '')
$errmsg = 'Please enter your message';

// ... more code here

The PHP validation is doing the same thing as the javascript validation. It check each value to see if it's empty and if it is we consider that as an error. We also recheck the validity of the email address.

When we find an error we set the value of $errmsg. We will print this value so the user can fix the error.

If everything is okay the value of $errmsg will be blank. So we continue processing the input.

// ... previous validation code

if($errmsg == '')
$subject = stripslashes($subject);
$message = stripslashes($message);

$to = "email@yourdomain.com";
$subject = '[Contact] : ' . $subject;
$msg = "From : $sname \r\n " . $message;
"From: $email\r\nReturn-Path: $email\r\n");

// ... more code here

Some web host set the PHP directive magic_quotes_gpc to 'on' which runs addslashes() to every GET, POST, and COOKIE data so we got an extra work to strip the slashes from the input.

Because the addslashes() function only add slashes before single quote ( ' ), double quote ( " ), backslash ( \ ) and NULL, we only need to worry about the $subject and $message. This is because (usually ) only these two can contain such characters. However, we can't be sure if magic_quotes_gpc is On or Off so we have to check it's value first using the get_magic_quotes_gpc() function

After finishing all that boring job of validating the input we finally come to the last, and the most important step, sending the message using the mail() function.

The first parameter we pass to the mail() function is the receiver's email address. The second is the email subject. The third is the message itself and the fourth is an additional headers.

I'm sure you already understand the purpose of the first three parameters so I'll just discuss about the fourth one, the additional parameter ( additional headers )

"From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"

Each headers are separated by the "\r\n" ( newline ) characters. The first two ( From and Reply-To ) is self explanatory. But what about the third one ( Return-Path )?

The reason is some spam filter will check the Return-Path header and compare it with the From header. If these two don't match then the email is considered as spam and you're email won't get delivered ( or sent to the spam folder ). So it's better to play safe and put Return-Path header when we want to send an email to make sure it gets delivered.
Recent Comments
By: edw Posted on 12-20-2008 2:58 PM

Wow, this was some great stuff. I was looking at a general concept for validating an email address.

I have a customer table that when they create an account, I don't want repeat entries. In other words,

if the enter their email address and it already exists, I want it to return with, there is an account with this email address already............go to forget your user name/ password.

Should I use if ($_POST[emai]) array to check? Should I do a select statement to the mySQL database, and if returns with a row, so it is true, give the error message?

Any code or advice would be great.
By: edw Posted on 12-20-2008 8:06 PM

Here is the function I created to check the database for a dupe email address:

// if returns true success, false means there were dupe emails.

function checkEmailDupes($email) {

global $connection;

$UCemail = strtoupper($email);

$query = "SELECT email FROM customer

WHERE upper(email) =


$checkEmail = mysql_query($query, $connection);


$numRows = mysql_num_rows($checkEmail);


return true;

} else {

return false;



then i use the function:

$EmNoDup =false;


$EmNoDup =true;

}else {



echo "";


if(empty($errors) && $EmNoDup == true ) {

$query = "INSERT INTO customer (............................and so on.

Does this look like a generally accepted code? I am quite new.............thanks KP

1 komentar:

  1. Mohon ijin berpromosi. service Ac segala jenis merk. kami service Ac mencakup wilayah coverage seluruh Surabaya, Gresik, Sidoarjo. kami juga menerima jasa service perbaikan AC bongkar dan pasang AC. pekerjaan kami cepat, tepat, profesional, harga kompetitif di banding harga jasa luaran.
    service ac split sidoarjo
    tukang service ac sidoarjo
    service ac surabaya sidoarjo
    service ac surabaya selatan
    service ac surabaya timur
    service ac surabaya barat
    service ac surabaya utara
    service ac kota surabaya



    Segera hubungi kami, dan kami akan datang kerumah Anda 24 Jam Non Stop.
    (Hari Sabtu / Minggu / Hari Libur buka)
    PIN BBM : 54BE0B4B / 5474CD93 / TELP : 085645475574