Welcome Guest ( Log In | Register )



2 Pages V   1 2 >  
Reply to this topicStart new topic
> PHP Tutorial: Form Verification And Simple Validation, A One Page script for PHP form verification.
Rating 4 V
Houdini
post Mar 4 2006, 06:10 AM
Post #1


Super Member
Group Icon

Group: Members
Posts: 572
Joined: 25-April 05
From: Nashville Tennessee
Member No.: 4,340



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.

CODE
<?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.

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

This post has been edited by Houdini: May 23 2006, 11:50 AM
Go to the top of the page
 
+Quote Post
dinosaur
post Oct 3 2006, 02:05 PM
Post #2


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 1
Joined: 3-October 06
Member No.: 16,322



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?

This post has been edited by dinosaur: Oct 3 2006, 02:18 PM
Go to the top of the page
 
+Quote Post
mastercomputers
post Oct 4 2006, 06:13 AM
Post #3


PESTICIDAL MANIAC
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



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
Go to the top of the page
 
+Quote Post
bakr_2k5
post Dec 4 2006, 05:22 PM
Post #4


Member - Active Contributor
Group Icon

Group: Members
Posts: 83
Joined: 25-September 06
From: The Netherlands
Member No.: 16,153



CODE
else {
  echo "<span style=color:red>$error</span>";
}
I would change this to
CODE
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 wink.gif)
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.
CODE
$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
CODE
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
CODE
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 wink.gif
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 dry.gif

Bakr_2k5

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

This post has been edited by bakr_2k5: Dec 4 2006, 05:27 PM
Go to the top of the page
 
+Quote Post
livingston
post Mar 21 2007, 07:27 PM
Post #5


Advanced Member
Group Icon

Group: Members
Posts: 149
Joined: 14-February 07
From: Tuticorin, India
Member No.: 20,415
myCENTs:0.55



thanks for this nice tutorial, this will be very useful for me in developing the CMS for my website.
Go to the top of the page
 
+Quote Post
mastercomputers
post Apr 7 2007, 11:51 PM
Post #6


PESTICIDAL MANIAC
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



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
Go to the top of the page
 
+Quote Post
matthewk
post May 29 2007, 12:06 AM
Post #7


Member [ Level 1 ]
Group Icon

Group: Members
Posts: 47
Joined: 24-May 07
Member No.: 22,128



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 smile.gif
Go to the top of the page
 
+Quote Post
ossanzi
post Aug 19 2007, 03:30 PM
Post #8


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 8
Joined: 19-August 07
Member No.: 24,196



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...
Go to the top of the page
 
+Quote Post
iGuest
post Nov 21 2007, 10:00 PM
Post #9


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



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
Go to the top of the page
 
+Quote Post
mastercomputers
post Dec 17 2007, 01:23 AM
Post #10


PESTICIDAL MANIAC
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



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
Go to the top of the page
 
+Quote Post

2 Pages V   1 2 >
Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. PHP: Writing A Generic Login And Register Script(15)
  2. Simple User Validation Script(5)
  3. Very Simple Login-script(18)
  4. Attack Script In Php(5)
  5. A Simple Register Script(3)
  6. Creating A Php Login Script(3)