Jump to content

Welcome to AstaHost - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!

Toggle shoutbox Shoutbox Open the Shoutbox in a popup

@  yordan : (14 April 2014 - 05:28 PM) By The Way, This Could Be An Interesting Subject For A Topic, What About Posting This Question? Let's See If Other People Have The Same Feeling Concerning Bootlists!
@  yordan : (13 April 2014 - 09:36 AM) Boot Order : Cd, [Usb,] Hard Drive :D
@  yordan : (11 April 2014 - 07:23 PM) I Simply Let The Bios Do That
@  Ritesh : (11 April 2014 - 10:23 AM) Is It Possible To Launch Fedora Live Cd Or Installation Disk From Hard Drive On Windows Platform Using Grub Mbr File.
@  Ritesh : (11 April 2014 - 10:21 AM) No U Are Not.. Btw.. I Have Question For You.
@  yordan : (10 April 2014 - 08:02 AM) You Are Partially Right.
I Was Not.
Nevertheless, I Am Again :)
@  Ritesh : (09 April 2014 - 07:33 PM) :P
@  Ritesh : (09 April 2014 - 07:33 PM) I Think U R Not..
@  yordan : (09 April 2014 - 09:28 AM) I'm The Master Of The Shoutbox!
@  yordan : (05 April 2014 - 10:32 PM) He-He
@  Ritesh : (04 April 2014 - 06:59 PM) Ha Ha Ha ....
@  yordan : (04 April 2014 - 11:15 AM) Welcome Back, Starscream!
@  yordan : (03 April 2014 - 02:31 PM) And I Hope That He Will Come Back Soon :)
@  yordan : (01 April 2014 - 02:53 PM) Nice, Ritesh Came, I'm Not Home Alone Today.
@  Ritesh : (01 April 2014 - 08:51 AM) Oh!!! Poor Dear Yordan..
@  yordan : (31 March 2014 - 10:02 AM) I'm A Poor Lonesome Cow-Boy
@  yordan : (27 March 2014 - 02:22 PM) He Is Unpatient Due To His Patients!
@  Ritesh : (27 March 2014 - 10:46 AM) :(
@  Ritesh : (27 March 2014 - 10:46 AM) He Is Busy With His Patients.
@  yordan : (26 March 2014 - 08:12 PM) Ahsani, Where Are You?

* * * * - 1 votes

PHP Tutorial: Form Verification And Simple Validation A One Page script for PHP form verification.

16 replies to this topic

#1 Houdini


    Super Member

  • Members
  • 572 posts
  • Location:Nashville Tennessee

Posted 04 March 2006 - 06:10 AM

Having used various means of verifying HTML forms I believe that this method of verifying a form to be the best mostly because it does everything on one page. It presents the form on one page and then when the submit button is pressed, if all the required fields are not filled out then it will present the form again with all the fields intact and in red lettering will point out the fields that are required to be filled out in red. It is not possible to click submit using this method even if the user has turned JavaScript off. While it is possible to use javascript to verify that all fields are filled out, if the user has turned off Javascript this method will not work any way. This is done using PHP and if you are hosted with Astahost then why not go ahead and use it. The only thing this form will not do is repopulate checkboxes since they are usually an indexed array (but don't have to be , they could be associative) and I have another method for that but that is for later. You can take this script and modify it after seeing how it works and make it perform the way you would like for it to. This method will use both HTML and PHP in the same page so lets get started.

<?php /* this is guarunteed to work it is possible to use <? (short tags but this style works everywhere).*/
/*Only verify/validate form when it is submitted program name: form.php */
  $error='';//initialize $error to blank
  if(trim($_POST[username])=='' || strlen(trim($_POST[username])) < 6 ||strlen(trim($_POST[username])) >12){
	  $error.="Please enter a username between 6 and 12 characters!<br />"; //concatenate the $error Message with a line break 
  if(trim($_POST[password])=='' || strlen(trim($_POST[password]))< 6){
	  $error.="Your password must be at least 6 characters in length!<br />";//concatenate more to $error  
	$error.="An email address is required!<br />"; 
	  else {
		if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST[email])) { 
		$error="The e-mail you entered was not in the proper format!"; 
  if($error==''){//Hmmmm no text is in $error so do something else, the page has verified and the email was valid
  // so uncomment the line below to send the user to your own success page or wherever (swap yourpage.php with your files location). 
  //echo "script type=\"text/javascript\">window.location=\yourpage.php\"<script>";  
	   echo "<span style=color:red>$error</span>";
That ends the PHP part of the script except for some PHP echos in the HTML section. The first line of code checks to see if the submit button has been pressed, it won't do anything unless submit has been pressed so then the code goes right to the HTML part below thiese explainations. The next two if conditional statements check that if the user name and password meet the conditions following the if. In the case of the username if it is equal to '' (blank) OR if the length of the string after PHP has trimmed trailing whitespace is < (less than) 6 OR if the length of username is > (greater than) 12 then it will add to the $error variable and display the message in red because of the style embedded in the script. The || means OR in PHP and in the second if condition it works the same as the username only it requires at least 6 letters or letters and numbers or any printable character.

The verification and validation requires a little more explaination becuase it uses a regular expression to test for a valid email address. The first part of the email just checks to be sure that they even enter something and if they did then the else statement checks to see that the email is in a valid format namely a group or alphanumeric or printable charactersthen a "@" symbol then more alphanumeric characters and a "."followed by alphabetic characters. the "," seperating the regex then gives the second part with is theemail to check against. If this test fails then the user will see the form redisplayed with the message "The email you entered was not in the proper format!" will show in red.

If there are no errors the last if condition checks if the $error variable is empty or blank and if so then you would remove the comment the(//) in front of the echo "<.... and change the URL to the page you want the user to use. Finally all the concatenated
$errors are printed by the else statement. So now all that is left is to write the HTML form. and it is below and is tacked just below the code above these explainations. NOTE Just copy and paste the first section of code and then copy and paste the HTML below right after the the ?> closing tag.

<form  action="form.php" method="post">
<table border="1" cellpadding="2" bgcolor="azure"><!--Put a nice border areound the table and add soft color-->
	<td width="20%" align="right">First Name</td>
	<td width="80%">
	<input type="text" name="firstname" size="20" value="<?php echo  $_POST[firstname] ?>"></td><!--NOTICE the php in the values-->
	<td width="20%" align="right">Last Name</td>
	<td width="80%">
	<input type="text" name="lastname" size="20" value="<?php echo $_POST[lastname] ?>"></td><!--will echo users input for repopulation-->
	<td width="20%" align="right">Username</td>
	<td width="80%">
	<input type="text" name="username" size="20" value="<?php echo $_POST[username] ?>"> (must be between 
	6 an 12 characters)</td>
	<td width="20%" align="right">Password</td>
	<td width="80%">
	<input type="password" name="password" size="20" value="<?php echo $_POST[password] ?>"> 
	(Password must be at least 6 characters)</td>
	<td width="20%" align="right">E-mail</td>
	<td width="80%">
	<input type="text" name="email" size="40" value="<?php echo $_POST[email]; ?>"></td><!--Give more room for long emails-->
	<td width="20%" align="right"> </td>
	<td width="80%">
	<input type="submit" value="" name="submit"></td>
<h3>The Username Password and the E-mail fields are required!</h3>

Using the code above as a model you can modify it to suit your needs for your own site. The regex used to validate I found at the Zend site and is meant to work with .be or .any two or three character extension in a URL I have just finished working on a script that repopulates checkbox data. After looking all over the net for a tutorial or even asking in forums to make it work, I built my own that works like I want, so if there are enough requests I will post it along with explainations and comments. It takes four pages of code to work, but two of them are almost identical it is just that one inserts data and the other updates the database.

Edited by Houdini, 23 May 2006 - 11:50 AM.

#2 dinosaur


    Newbie [ Level 1 ]

  • Members
  • 1 posts

Posted 03 October 2006 - 02:05 PM

Nice simple and logical!
but does it work? When I try it verbatim, it posts my form.php even if all the fields are left blank.
Any thoughts?

Edited by dinosaur, 03 October 2006 - 02:18 PM.

#3 Guest_mastercomputers_*

  • Guests

Posted 04 October 2006 - 06:13 AM

Nice write up, but I have to disagree with it security wise.

What you failed to do was insure that the form posted is actually that form being used. I could create a form and send it directly to that page and it'll be processed as long as it fits the requirements of having $_POST['submit'] set which is simple enough.

Now how would you actually verify that what this script is processing is indeed the allowed form?

If you want to give it a shot at writing that up, then you should and I'll tell you whether it's correct or not or better can be improved.

As for processing the form within the same page being the "best" method, that's debatable but I won't go into it, I prefer talking about and finding "best" practices but never claiming them to be the best method in using, but as long as they serve their purpose well and do not create too much server load, it should be fine.

Just some syntax problems, you should always quote inside arrays ($_POST, $_GET, etc) if the key you're refering to is a 'string'. What you've done with $_POST[submit] actually tells PHP to look for a key within $_POST with a constant called submit, when it's not found it'll produce a warning, and then tell you what it attempted to use, which might be the 'string' next which would be correct in it's assumption, but if there was no 'string' in that array, then what would you expect? I think it checks for variables next, but I'm not sure, I haven't actually looked at the ordering that PHP checks undefined variables and constants.

Another thing you forget to do is actually check whether $_POST['username'] (and the other variables) is set before using a evaluation condition, so again you could be calling an undefined key inside $_POST which results in another warning message.

Because you call trim() so many times with the same variable, you may as well create a variable for it that's trimmed already so you don't keep repeating the trim() function everytime.

Let's evaluate your regular expression now, how many email addresses do you know start with _ or - or numbers as a first character? It could be possible, I did read the RFC on this and wrote a pattern based entirely on what the RFC stated but I altered it to be more realistic since the RFC was quite flexible and allowed things that most emails created now would never allow.

Also, at the end, you expect emails to end in either 2 or 3 characters, you can now have email addresses that end in .info .govt etc and they will not be allowed in your pattern.

Anyways, I hope you do provide solutions to these problems including in your form, as you must check variables are set before using them, so those variables also will result in errors when you first appear on that site, as they would not exist yet.



#4 bakr_2k5


    Member - Active Contributor

  • Members
  • 83 posts
  • Gender:Male
  • Location:The Netherlands
  • Interests:Computing, Gaming, Programming and Websurfing :)

Posted 04 December 2006 - 05:22 PM

else {
  echo "<span style=color:red>$error</span>";
I would change this to
else {
  echo "<span style=color:red>$error</span>";
  include("./html_form.php"); // Or whatever the page with the html form thing is called!
(note: please scroll a bit down to my EDIT thing if you're mad about it :P)
This prints the $error's and the html form (with the values) on the screen.
If you don't do this, and hit the back button, it gives that annoying pop up about "POST already sent" or something like that.

And as mastercomputers said, those trims()'s could be much less.
$username = trim($_POST['username']);
$_POST['username'] = trim($_POST['username']);
For the javascript redirection at the end, use META tags or PHP "header()" function, since not everyone has javascript enabled.

Lastly a little correction
else {
  if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST[email])) {
	$error="The e-mail you entered was not in the proper format!"; 
Should be
else {
  if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST[email])) {
	$error.="The e-mail you entered was not in the proper format!"; 
If you don't see it, the dot after $error :P
As for the "eregi()" thing, don't know anything about it, but mastercomputers said it had to be changed.

Oh man I feel bad now :P


For the first change, never mind! I didn't know it was a "one page script", sorry about that :P

Edited by bakr_2k5, 04 December 2006 - 05:27 PM.

#5 livingston


    Advanced Member

  • Members
  • 149 posts
  • Gender:Male
  • Location:Tuticorin, India
  • myCENTs:0.55

Posted 21 March 2007 - 07:27 PM

thanks for this nice tutorial, this will be very useful for me in developing the CMS for my website.

#6 Guest_mastercomputers_*

  • Guests

Posted 07 April 2007 - 11:51 PM

Well, I don't see no solutions to what I suggested so I'll provide clues.

To check if a form is actually the form you want to process, you need to make sure that the form resides where you've placed it. You can check that the form is actually coming from the server it's hosted on by checking it's referrer which should indicate either the server's domain or ip address.

I prefer separating PHP from HTML, it's easier to read and to alter, though there will be times where you have to include PHP inside HTML to get what you need to happen, it's probably a lot better than on the fly re-writing.

If using an unknown constant in an array, a warning will be produced, it will then check for a string, if that does not exist an error will be produced. That's it, there's no more it can do for you so just ensure it's correct so you don't have these problems. error_reporting should be turned on when testing scripts out so you can fix the problems before letting them loose on the internet.

Since you wrote the form up, you know which variables should be there and you should know which variables to check. What you want to do first is eliminate all the characters and malformed exploit attempts you don't want to allow, rather than limiting what can be used. Every so often you should get use to checking your database, etc just to insure that you prevented what you didn't want to happen, if not, you have to rethink your script. After you've eliminated the characters you don't want, check if it's empty, check that it fits the type of information you're wanting, follows the format you wanted and after you're completely happy with it, store it in a variable. If for any reason you're not happy with it, append it in an error message, change a flag to ensure your script when it gets near the end, does not go through with the output, which could be, login or storing in database, etc. You then just present back on the form, the errors you gathered and tell them to fix them up before they proceed. I would suggest using Javascript to eliminate a lot of the simple checks, so your server isn't going to waste it's time (this does not mean avoid server checking of what the javascript does).

Don't suggest using short tags, I'm still against this practice and am trying to have it removed in later PHP versions but this message needs to be spread more or else people will no longer know what's going on, it's a pity we can't rewrite the books that are out there that show this usage.

When you're reusing a form to fill in data you've already received, insure the information is checked first and actually does exist to avoid warning messages.

As for the regular expression, this is the hardest to explain without writing code, but I'm going to try!

All emails should start with a letter from a to z in any case (I don't cater for anything other than English right now), afterwards you can have dashes, numbers, dots, letters, etc. It should then be followed by the @ symbol, next the format is harder to know. Usually I base it on domain formats, which some can contain numbers at the start, but not special characters, it can have many dots and the length does not need to be fixed though I try to limit what it can, after a dot however, should follow characters. There's also length restriction, but not so important as it's quite large but you should limit the minimum amount to at least 1 character and I think someone with an email address too long should change their email to something a lot easier, and you can tell them that in your form if you like. Overall, there's only 1 @ symbol allowed, a suitable max length would be about 255 characters. The ending bit should not be limited so allow for many dots and ensure characters follow afterwards and that the last dot, there's only 2 to 5 characters, unless you've discovered longer endings for domains (so far I haven't encountered it).

I will provide coding solutions to help later on and hopefully show a cleaner way of presenting the form by separating the PHP from the HTML.



#7 matthewk


    Member [ Level 1 ]

  • Members
  • 47 posts

Posted 29 May 2007 - 12:06 AM

This is good, man. I think it would be even better if you could incorporate javascript usage too. So, If the user does not have javascript disabled, a page refresh would not be needed to validate. I look forward to seeing your work on the checkboxes and drop down boxes too! Keep up the good work B)

#8 ossanzi


    Newbie [ Level 1 ]

  • Members
  • 8 posts

Posted 19 August 2007 - 03:30 PM

If you know how to work with regular expressions and ereg()-eregi() functions of php you can validate every kind of form entries
But it is really hard to learn regular expressions...

#9 Guest_FeedBacker_*

  • Guests

Posted 21 November 2007 - 10:00 PM

Mastercomputers - Most universities or tertiary institutions (in Australia anyway) use numbers as the first character in their email addresses. Each student will have their student number as their email addresses (ie mine is 1336***5@student.curtin.edu.au ) So it is possible, and common for email addresses to start with numerals. I do agree with your other comments though.

What I do is set a flag using js to let my php script know that js has validated the form. This avaiods validating the form twice, but if the user has js disabled, then PHP validates the form.


#10 Guest_mastercomputers_*

  • Guests

Posted 17 December 2007 - 01:23 AM

My comments on email validation were based on the major free email address providers like yahoo, gmail and hotmail. If I track down my script on the RFC email address validation I created you probably would be surprised to see even the existence of special characters being allowed at the start, but we have to draw a line somewhere and so I only based it on these email providers, as they would probably have the largest audience, however it's not hard to alter the script to fit certain criteria.

However, this just means that if a legitimate email address is not being allowed, the form should allow them a way of contacting you so this issue can be resolved. You always have to have a fall back plan for everything.



#11 Andres Martinez Andrade

Andres Martinez Andrade

    Newbie [ Level 2 ]

  • Members
  • 19 posts
  • Gender:Male
  • Location:Mexico
  • Interests:Artificial Intelligence, Programming Contests like ACM, Programming &amp; Algorithms, Favorite languages Java, C++, PHP, Perl, Prolog, Scheme. Web Apps, Software Development, and more Geek's stuff...jaja

Posted 10 January 2008 - 06:34 AM

Well, I don't see no solutions to what I suggested so I'll provide clues.

To check if a form is actually the form you want to process, you need to make sure that the form resides where you've placed it. You can check that the form is actually coming from the server it's hosted on by checking it's referrer which should indicate either the server's domain or ip address.

If you check the referrer is enough to kick a hacker out or there exists another good practices for enhancing security in php scripts that process forms?

#12 TavoxPeru


    Super Member

  • [HOSTED]
  • 876 posts
  • Gender:Male
  • Location:Lima - Peru
  • Interests:Web and Software development, Internet, Computers, Electronic music, music, soccer.
  • myCENTs:13.21

Posted 28 March 2008 - 08:59 PM

If you check the referrer is enough to kick a hacker out or there exists another good practices for enhancing security in php scripts that process forms?

Checking the referrer is a good practice but in my opinion is not enough, because it can also be faked, for this situation you can implement some type of IP checking. If the IP has not visited the specific page shortly prior to calling the script, deny access. For example the following code can be used to get the user's IP address:


Another good practice for enhancing security in php scripts is to validate for the correct method -POST or GET- that you use in your form, it is recomended that never use the $_REQUEST variable, if you use it for your validations you don't know which method is used, because this variable can handle both methods.

For example, if you use the POST method to send your form, it is very easy to validate it with the following code:

   echo("Unauthorized attempt to access page.");
Best regards,

#13 Guest_iGuest-Rudolf_*

  • Guests

Posted 20 July 2008 - 02:33 AM

PHP GD Lib random code verification in numbers only please
PHP Tutorial: Form Verification And Simple Validation

GD Lib with PHP produces my verification code in random letters and numbers.
That exactly is my problem, the letters!
I want to use the contact form on a multi lingual webpage with UTF-8 encoded input possible - but forreign languages do not have english alphabets on their keyboards.

So I would like to know if it is somehow possible to chnage what GD Lib displays e.G to make it show only numbers.

Anyone having an idea??

-reply by Rudolf

#14 Guest_(G)azmi_*

  • Guests

Posted 28 June 2010 - 03:02 PM

verify to DBPHP Tutorial: Form Verification And Simple Validation

Hi ..

Nice and simple code . I tried this code and working .  From this code how :-

1. How to verify with database if all entry form form, were valid. Where to put varify against DATABASE code ?

2. After successfully verify with Database , how to continue with access to Main  Menu applicatipn system.


-reply by azmi


#15 Guest_(G)kevinanchi_*

  • Guests

Posted 20 August 2010 - 05:40 PM

JavaScript is very useful when it comes to checking HTML forms forValid entries. You can check that your visitors have filled in yourForms correctly before they're transmitted over the Internet. TheScripts are often activated when the Submit button is pressed. IfThere's a fault, they supress the transimission of the form contentsAnd show an error message.

#16 Guest_(G)BeeDee_*

  • Guests

Posted 16 November 2011 - 10:16 PM

Nice start, but lacking in too many areasPHP Tutorial: Form Verification And Simple Validation

Like not quoting array "subscripts". (this should ALWAYS be done)You should ALWAYS use mysql_real_escape_string() or some equivalent to prevent exploits when storing data in a database using SQL.There is no discussion of when you should or MUST use html_special_characters() or other similar functionality.You should also code for multiple/cross-browser support, so checking for isset($_POST[submit]) may not be enough, and will not work if the "submit button" is not an actual HTML type="submit".The original post was apparently written in 2006, so it's nice to at least see some more current information appended in the comments.

-reply by BeeDee

#17 Quatrux


    the Q

  • [HOSTED]
  • 1,669 posts
  • Gender:Male
  • Location:Lithuania, Vilnius
  • Interests:PHP, MySQL, Oracle, PL/SQL, HTML, CSS, Javascript, jQuery, C# Computers, Alternative OS, Amiga, MorphOS, Beer, Friends, Linux, KDE..
  • myCENTs:30.76

Posted 21 November 2011 - 07:06 AM

The best way to check if an email is valid is to send a confirmation email and if he got that email and will write down the confirmation email, you will know that his email is valid.

Even though it's possible to check the domain and etc. I saw those kind of scripts, but I never used them, I've read they're much slower, so who cares? If the user wants to register and use the service, he will use a valid email, otherwise he won't and you don't really need to care about it, a regular expression to at least check if the email is valid could be like this:

if (!preg_match("/^([a-z0-9._-pL](+[a-z0-9pL])*)+@[a-z0-9.-pL]+.[a-zpL]{2,6}$/iu", $Email))
// Error

This is one of the best regexp's I've found on the Internet some years ago, if someone is using not a regular email, it's his own problem.

Furthermore, there are services like 10min email: http://10minutemail....Mail/index.html

With which you will go through a confirmation email, but later you won't ever send him an email, it's a users choice to use such an email, I use it myself, whenever I want to only once do something, download or read something and when I need to register to a service I don't care, I use this email and it's really comfortable, you could always write scripts to prevent emails from some domains which are used by this servers, but it's extra job for minor things.

Reply to this topic


0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users