Jump to content
xisto Community
Houdini

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

Recommended Posts

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 Xisto 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 */if(isset($_POST[submit])){  $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    }   if(trim($_POST[email])==''){	$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>";    } 	else{	   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-->  <tr>	<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-->  </tr>  <tr>	<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-->  </tr>  <tr>	<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>  </tr>  <tr>	<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>  </tr>  <tr>	<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-->  </tr>  <tr>	<td width="20%" align="right"> </td>	<td width="80%">	<input type="submit" value="" name="submit"></td>  </tr></table><h3>The Username Password and the E-mail fields are required!</h3></form>

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 (see edit history)

Share this post


Link to post
Share on other sites

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.Cheers,MC

Share this post


Link to post
Share on other sites

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']);or$_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

 

Bakr_2k5

 

EDIT:

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

Edited by bakr_2k5 (see edit history)

Share this post


Link to post
Share on other sites

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.Cheers,MC

Share this post


Link to post
Share on other sites

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)

Share this post


Link to post
Share on other sites

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.-alex

Share this post


Link to post
Share on other sites

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.Cheers,MC

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites

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:
<?php$ip=$_SERVER["REMOTE_ADDR"];?>

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:

<?phpif($_SERVER['REQUEST_METHOD'] != "POST"){   echo("Unauthorized attempt to access page.");   exit;}?>
Best regards,

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
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.

TQ  

-reply by azmi

 

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.