By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,474 Members | 1,283 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,474 IT Pros & Developers. It's quick & easy.

Getting Started with Server-Side Validation

P: 17
Ok, i am trying to create a php model for a website I am creating. The php script must have a validation script to check form, a image verification script and a submission of the information to a database. So far, i have read many half written tutorials that explained things but not in detail. I am asking either for personal one on one help with this or a point in the right direction as to how to accomplish this. So far this is the code i have for my work, its not much but i suppose its a start. Would love the help of this forum to get me past these issues. Thank you very much.

[PHP]<? php

//Determine if the sumbit button has been clicked. If so, begin validating form data.

if ($_POST['submitB'] == "Submit")
{
//Determine if a Name was entered

$valid_form = true;

if ($_POST['name'] == "")
{
echo "Enter your name";
$valid_form = false;
}

else
{
$name = $_POST['name'];
}

if ($_POST['uname'] == "")
{
echo "Enter a user name";
$valid_form = false;
}

else
{
$username = $_POST['uname'];
}

if ($_POST['pass'] == "")
{

echo "Enter a password";
$valid_form = false;

}

elseif (strlen($_POST['pass']) < 4)
{

echo "Password must contain at least 4 characters";
$valid_form = false;
}

else
{
$password = $_POST['pass'];
}


//if all form fields were submitted properly, begin processing

if($valid_form == true)
{

//form processing code goes here

}
}
?>
[/PHP]

I have all kinds of inputs for the form, including a confirm password. Hopefully someone can help.
Aug 3 '07 #1
Share this Question
Share on Google+
34 Replies


pbmods
Expert 5K+
P: 5,821
Heya, speckledapple. Welcome to TSDN!

Let's see what we can do to help you out.

What do you want your code to do? Give an example.
What is your code doing that you don't want it to do? Give an example.
What is your code *not* doing that it is supposed to? Give an example.
Aug 3 '07 #2

P: 17
Well to answer the first question I want the code to take values from my form and validate each one. Now as you will see in the code i posted here( not the previous one) i managed to check for values if certain text inputs were empty. However, i am having trouble figuring out how to accept the input values for two radio buttons ( male or female) and birth month, day and year drop down menus. I have also done the coding for requiring no less than 6 inputs for the id and password fields but havent checked for spaces which i want none. Also accepting the input for a check box. Further more noting that not all inputs are required, i only checked empty values for those ones that are required.

[PHP]
<? php

$first = $_POST[\'firstName\'];
$last = $_POST[\'lastName\'];
$country = $_POST[\'countryId\'];
$gender = $_POST[\'genderId\'];
$city = $_POST[\'cityId\'];
$bmonth = $_POST[\'birthMonth\'];
$bday = $_POST[\'birthDay\'];
$byear = $_POST[\'birthYear\'];
$ethoid = $_POST[\'ethoId\'];
$email = $_POST[\'emailId\'];
$pass1 = $_POST[\'pass1\'];
$pass2 = $_POST[\'pass2\'];
$verimage = $_POST[\'verId\'];
$agree = $_POST[\'agreeId\'];

if (($pass1)!=($pass2))
{
header("Location: error-pwrverify.php");
Die();
}

function CheckMail($email)
{
if (eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,4}$",$email))
{
return true;
}
else
{
return false;
}
}
if ((empty($email)) || (!CheckMail($email)))
{
header("Location: error-email.php");
Die();
}

if (empty($first))
{
header("Location: error-first.php");
Die();
}

if (empty($last))
{
header("Location: error-last.php");
Die();
}

if (empty($country))
{
header("Location: error-country.php");
Die();
}

if (empty($ethoid))
{
header("Location: error-id.php");
Die();
}

if (empty($pass1))
{
header("Location: error-password.php");
Die();
}

if (empty($pass2))
{
header("Location: error-password.php");
Die();
}



$min_lenngth = 6;
if(strlen($ethoid) < $min_lenngth || strlen($pass1) < $min_lenngth)
{
header("Location: error-short.php");
Die();
}
?>

[/PHP]
Aug 4 '07 #3

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

I'm curious as to why you escaped your quotes when referring to $_POST indexes.
Aug 4 '07 #4

P: 17
Heya, speckledapple.

I'm curious as to why you escaped your quotes when referring to $_POST indexes.

what do you mean? each $_POST index has quotes around it.
Aug 4 '07 #5

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

what do you mean? each $_POST index has quotes around it.
Yes, but I'm curious why you escaped the quotes.

I.e.,
Expand|Select|Wrap|Line Numbers
  1. $first = $_POST[\'firstName\'];
  2.  
instead of
Expand|Select|Wrap|Line Numbers
  1. $first = $_POST['firstName'];
  2.  
Aug 4 '07 #6

P: 17
Heya, speckledapple.



Yes, but I'm curious why you escaped the quotes.

I.e.,
Expand|Select|Wrap|Line Numbers
  1. $first = $_POST[\'firstName\'];
  2.  
instead of
Expand|Select|Wrap|Line Numbers
  1. $first = $_POST['firstName'];
  2.  


ouch u got a point, i didnt even realize that. thx for the correction. but im sstill having issues with how to do the other stuff
Aug 5 '07 #7

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

Ok. So:

Expand|Select|Wrap|Line Numbers
  1. <? php
  2.  
  3. $first = $_POST['firstName'];
  4. $last = $_POST['lastName'];
  5. $country = $_POST['countryId'];
  6. $gender = $_POST['genderId'];
  7. $city = $_POST['cityId'];
  8. $bmonth = $_POST['birthMonth'];
  9. $bday = $_POST['birthDay'];
  10. $byear = $_POST['birthYear'];
  11. $ethoid = $_POST['ethoId'];
  12. $email = $_POST['emailId'];
  13. $pass1 = $_POST['pass1'];
  14. $pass2 = $_POST['pass2'];
  15. $verimage = $_POST['verId'];
  16. $agree = $_POST['agreeId'];
  17.  
  18. if (($pass1)!=($pass2))
  19. {
  20.     header("Location: error-pwrverify.php");
  21.     Die();
  22. }
  23.  
  24. function CheckMail($email)
  25. {
  26. if (eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,4}$",$email))
  27.     {
  28.         return true;
  29.     }
  30.     else
  31.     {   
  32.         return false;
  33.     }
  34. }
  35. if ((empty($email)) || (!CheckMail($email)))
  36. {
  37.     header("Location: error-email.php");
  38.     Die();
  39. }
  40.  
  41. if (empty($first))
  42. {
  43.     header("Location: error-first.php");
  44.     Die();
  45. }
  46.  
  47. if (empty($last))
  48. {
  49.     header("Location: error-last.php");
  50.     Die();
  51. }
  52.  
  53. if (empty($country))
  54. {
  55.     header("Location: error-country.php");
  56.     Die();
  57. }
  58.  
  59. if (empty($ethoid))
  60. {
  61.     header("Location: error-id.php");
  62.     Die();
  63. }
  64.  
  65. if (empty($pass1))
  66. {
  67.     header("Location: error-password.php");
  68.     Die();
  69. }
  70.  
  71. if (empty($pass2))
  72. {
  73.     header("Location: error-password.php");
  74.     Die();
  75. }
  76.  
  77.  
  78.  
  79. $min_lenngth = 6;
  80. if(strlen($ethoid) < $min_lenngth || strlen($pass1) < $min_lenngth)
  81. {
  82.     header("Location: error-short.php");
  83.     Die();
  84. }
  85. ?>
  86.  
I love how you have a genderID, by the way. Just in case we ever come up with a third gender, your code is covered :P

Alright. For checking dates and times, you'll probably find it useful to compare the data returned by strtotime().

In terms of radio boxes, try
Expand|Select|Wrap|Line Numbers
  1. print_r($_POST)
to see what each checkbox sends with the form.
Aug 5 '07 #8

kovik
Expert 100+
P: 1,044
Please check all variables with isset() or empty before using them (this means BEFORE assigning the $_POST data to a variable) and use full URLs with the 'Location:' header, 'http://' and all, or it will not obey the RFC standards, which also means that browsers aren't required to know where you are trying to redirect to, which can cause problems in certain browsers.
Aug 5 '07 #9

P: 17
Expand|Select|Wrap|Line Numbers
  1. if ($gender == "") {
  2.  
  3.     header("Location: error-gender.php");
  4.     Die();
  5. }

Ok i used this code to check if my gender radio boxes were not selected because the values of each box is male and female respectively. But it doesnt work. I also want to try and check for spaces in the username,id and password input fields. I also want to incorporate the agree to terms of service checkbox but its in different form so i dont know how unless i inport it or make it global.
Aug 5 '07 #10

kovik
Expert 100+
P: 1,044
Ok i used this code to check if my gender radio boxes were not selected because the values of each box is male and female respectively.
Then test. Add "print_r($_POST)" to your results and post the form without selecting a gender to see what you get.

I also want to try and check for spaces in the username,id and password input fields.
You may be interested in the character type functions, such as ctype_alnum().

I also want to incorporate the agree to terms of service checkbox but its in different form so i dont know how unless i inport it or make it global.
Why separate the forms...?
Aug 6 '07 #11

P: 17
Ok i decided to just switch the gender input to text input fields cause i couldnt figure out the radio buttons. Now im trying to display error messages to each of the fields. However, i decided it would be easier just to make all the errors go to one page and just display the field thats in error. This is the code im trying to use.

[PHP]$msg = "";

if (empty($gender))
{
$msg = 'You did not enter properly';
header("Location: error.php");
Die();
}[/PHP]


And this is the way i display it on the error page:
[PHP]<?php
if(isset($msg)){
echo $msg;
}
?>[/PHP]

So far it shows up a blank page. Im trying to get it so i can output different error messages using one variable depending on if the statement is true. That way i can just cut down on making a billion error pages for each one.
Aug 6 '07 #12

kovik
Expert 100+
P: 1,044
Ok i decided to just switch the gender input to text input fields cause i couldnt figure out the radio buttons.
... That's just lazy. You've disappointed me.

Now im trying to display error messages to each of the fields. However, i decided it would be easier just to make all the errors go to one page and just display the field thats in error.
It'd actually be easier to display the errors on the same page as the form so that you can easily allow them to fix the errors.

[PHP]$msg = "";

if (empty($gender))
{
$msg = 'You did not enter properly';
header("Location: error.php");
Die();
}[/PHP]


And this is the way i display it on the error page:
[PHP]<?php
if(isset($msg)){
echo $msg;
}
?>[/PHP]
And how, exactly, do you expect $msg to get to error.php? $msg only exists on the page that you create it on. When you alter the 'Location' header, you are changing the page that you are on, not just the visual aspects.

So far it shows up a blank page. Im trying to get it so i can output different error messages using one variable depending on if the statement is true. That way i can just cut down on making a billion error pages for each one.
All you need is one page to hold the form, process the form, and show errors regarding the processing of the form.
Aug 6 '07 #13

nathj
Expert 100+
P: 938
...
All you need is one page to hold the form, process the form, and show errors regarding the processing of the form.

Sounds like AJAX to me. This would enable you to validate any item you wish as the user enters, including checking against the database.

If you want an example of this is in practice visit my site - currently under development.

It means that the user can see what is wrong and they are only allowed to proceed when the form is correct.

It is also good practice (to put it lightly) to validate the data server side as well.

Cheers
nathj
Aug 6 '07 #14

P: 17
Ok update.....

I managed to go back and properly error check the gender radio buttons( yes i figured it out). I also managed to organize it so it all goes to one error page. Now im working on the database process section and i have it pretty much done except im getting this error when i submit my form. Tried changing a few things and taking out sections of code but it still errors. Theres nothing even on the line so im expecting its something else.

Parse error: syntax error, unexpected $end in /home/simpl64/public_html/ethos/confirm.php on line 189
Aug 7 '07 #15

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

That error means that you opened a curly brace somewhere and didn't close it.
Aug 7 '07 #16

P: 17
Thanks, its funny that it caused that. Anyway, i now have another error that I cant figure out because i know the syntax is right. But its providing an error as if its invalid.

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource

I have this on two statements in my code...
[PHP]$check = mysql_query("SELECT ethoId FROM member WHERE ethoId = '$ethoid'");
$returned = mysql_fetch_array($check);

if(!empty($returned))
{
echo " This user already exists!";
mysql_close($member);
Die();
}
else
{
$check = mysql_query("SELECT email FROM member WHERE emailId='$email'");
$returned = mysql_fetch_array($check);
if(!empty($returned))
{
echo " This email already is with another account!";
mysql_close($member);
Die();
}[/PHP]
Aug 7 '07 #17

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

Try adding this after every mysql_query:
Expand|Select|Wrap|Line Numbers
  1. echo mysql_error();
  2.  
You might also want to save your sql into a variable so you can output that, too. E.g.:
Expand|Select|Wrap|Line Numbers
  1. $sql = "SELECT ethoId FROM member WHERE ethoId = '$ethoid'";
  2. $check = mysql_query($sql);
  3. echo $sql, '<br />', mysql_error();
  4.  
Aug 7 '07 #18

P: 17
Ok back again and i seem to be rolling until i hit a bit of a snag. I am getting this error message....

Column count doesn't match value count at row 1

I used the mysql_error to figure that part out. Not understanding why im getting it though. This is the code i think its talking about...

[PHP]$pass1=md5($pass1);
$confirm_code = md5(uniqid(rand()));
$request = "INSERT INTO member values(NULL,'$first','$last','$gender','$country', '$city','$state','$bmonth','$bday','$byear', '$ethoid','$pass1','$email','$confirm_code')";
$results = mysql_query($request);
echo mysql_error();[/PHP]
Aug 10 '07 #19

P: 17
Disregard that last post, i got that working. Now im stuck though. This problem is a bit harder. I set up an email confirmation script that should update a column in my database when they click the link in their email. However, i am having trouble finding the right record. I think i got the selecting of the column down but the update statement doesnt compute because the ID column is not a variable in the script. So the "where" part in the update statement doesnt work. This is the script, im just trying to update one column out of 15.

[PHP]$yes = "yes";
// Retrieve data from table where row that match this passkey
$sql1 = "SELECT confirm_code FROM member WHERE confirm_code ='$passkey'";
$result1 = mysql_query($sql1);

if($result1){

// Count how many row has this passkey
$count=mysql_num_rows($result1);
if($count==1){

$sql2 = "UPDATE member SET confirmed = '$yes' WHERE id = 'id'";
$result2 = mysql_query($sql2);
echo $sql2, mysql_error();[/PHP]
Aug 10 '07 #20

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

Try this as your first query:
Expand|Select|Wrap|Line Numbers
  1. $sql1 = "
  2. SELECT
  3.         `id`
  4.     FROM
  5.         `member`
  6.     WHERE
  7.         `confirm_code` = '{$passkey}'
  8.     LIMIT 1";
  9.  
Then adjust the rest of your code where appropriate.
Aug 10 '07 #21

P: 17
I tried that and i see the problem just dont know how to tackle it. The issue seems that I have no variable to classify in the UPDATE line for id. I have an id column. But it doesnt update the confirmed column to a "yes" when the link is clicked. So i selected id from the table but how do i get into a variable that can be used in the update line so it knows which record im talking about? Because in its current form, if there was more than one record it would be a problem but its not even updating one record.

[PHP]$sql3 = "SELECT id FROM member WHERE confirm_code ='$passkey' limit 1";
$result1 = mysql_query($sql3);
if($result1){

// Count how many row has this passkey
$count=mysql_num_rows($result1);
if($count==1){
echo $sql3, '<br/>', mysql_error();
$sql4 = "UPDATE member SET confirmed = '$yes' WHERE id = '$sql3'";
$result2 = mysql_query($sql4);
}[/PHP]
Aug 10 '07 #22

pbmods
Expert 5K+
P: 5,821
Heya, speckledapple.

Hint:
Expand|Select|Wrap|Line Numbers
  1. $userdata = mysql_fetch_assoc($result1);
  2. print_r($userdata);
  3.  
Aug 10 '07 #23

P: 17
Ok, i have broken down the code step by step using the print_r and echo functions to have some kind of result print on the screen. While in the course of doing this i figured out that in the first part of the statement where it selects the records from the database, the resource id ends up always being 31. Obviously there is not 31 records in my database, its only one currently. so i think my problem is the actual selecting of the right ID and then to actually update a specific column in that row. So far ive just hit a nice large wall.

[PHP]$passkey=$_GET['passkey'];
$yes = "yes";
// Retrieve data from table where row that match this passkey
$sql3 = "SELECT id FROM member WHERE confirm_code ='$passkey'";
$result1 = mysql_query($sql3);
$userdata = $result1;


if($result1){

$sql4 = "UPDATE member SET confirmed = '$yes' WHERE id = '$userdata'";
$result2 = mysql_query($sql4);
print_r($sql4);
}
// if not found passkey, display message "Wrong Confirmation code"
else {
echo '<div class="error"> Wrong Confirmation Code!! </div>';
}

if($result2){

echo '<div class="error"> Your account has been confirmed.<br/>Welcome to <br/><strong>Ethos</strong>!!</div>';
mysql_close($member);
Die();
}[/PHP]
Aug 14 '07 #24

pbmods
Expert 5K+
P: 5,821
Heya, SpeckledApple.

Change this line:
Expand|Select|Wrap|Line Numbers
  1. $userdata = $result1;
  2.  
To this:
Expand|Select|Wrap|Line Numbers
  1. $row = mysql_fetch_assoc($result1);
  2. $userdata = $row['id'];
  3.  
Aug 14 '07 #25

P: 17
Ok since i last posted i have done very well in my php coding but now im kinda stuck again. But this time more in phpMyAdmin. Does anyone know how to link tables in that program because is surely cant find an option for it?
Aug 28 '07 #26

ak1dnar
Expert 100+
P: 1,584
Ok since i last posted i have done very well in my php coding but now im kinda stuck again. But this time more in phpMyAdmin. Does anyone know how to link tables in that program because is surely cant find an option for it?
Link Table in PhpMyAdmin? Could you please be more specific?
Aug 28 '07 #27

pbmods
Expert 5K+
P: 5,821
Heya, Speckled.

Changed thread title to better describe the problem; I don't know how we missed it for so long....

Are you trying to set up foreign key constraints?
Aug 28 '07 #28

P: 17
Well yea i am trying to link tables in a database in phpMyAdmin using foreign keys. But theres no specific option in that program to do it.
Aug 28 '07 #29

pbmods
Expert 5K+
P: 5,821
Heya, Speckled.

Are these InnoDB tables or MyISAM (check the operations page for an individual table)?
Aug 28 '07 #30

P: 17
its an MyISAM table but something tells me, or at least from what i have read, it seems like the other type is better. Especially for a forum that im building from scratch, thats my project btw :)
Aug 29 '07 #31

nathj
Expert 100+
P: 938
its an MyISAM table but something tells me, or at least from what i have read, it seems like the other type is better. Especially for a forum that im building from scratch, thats my project btw :)
Hi speckledapple,

At the risk of wading in a bit late on and of being somewhat contreversial I wouldn't bother linking the tables like that.

I've worked on huge databases, both web based and on desktop apps and never bothered with this explicit linking. As long as you know and document what the links are you can code with them in mind. You are then not reliant on something else.

I know there are many arguments against this but I prefer the extra control I get this way. As long as you know when you delete a record, for example, that you need to check other tables as well all will be fine.

As you appear to be building something from scratch you could certainly code this sort of checking in now in your data object and all will be well. It's certainly easier than figuring out PHPMyAdmin - which BTW I really dislike.

That's my take on this particular issue.

Cheers
nathj
Aug 29 '07 #32

pbmods
Expert 5K+
P: 5,821
I concur with Nathj.

MyISAM is faster than InnoDB, and good exception handling will negate the loss of transactions and foreign key constraints.
Aug 29 '07 #33

P: 17
OK i seem to be having a simple problem with date and time. At first i had one field to record both the date and time at the time of registration. But i split it into two columns, one date, one time. Though im quite sure the format i put forth is right, its still displaying either blank or wild numbers that obviously dont make any sense. For instance....
[PHP]$date = date("Y-m-d");
$time = time()[/PHP]
That is the code i wrote to put time and date into variables.

regDate
0000-00-00

regTime
838:59:59

And that is the output in the table. The time i know is way off cause i tried it twice and got the same number. And the date just displays 0 like its getting no information. Now the coding should give me current date and time but it doesnt.
Sep 3 '07 #34

pbmods
Expert 5K+
P: 5,821
Heya, Speckled.

time() outputs the current number of seconds since December 31, 1969 23:59:59, which is probably not what you are going for.

Try this instead:
Expand|Select|Wrap|Line Numbers
  1. $time = date('H:i:s');
  2.  
Sep 3 '07 #35

Post your reply

Sign in to post your reply or Sign up for a free account.