Page 1 of 3

Help Needed- user Input Validation

Posted: Fri May 01, 2009 3:25 pm
by phphelpseeker
I really need help. I'm new to PHP. I have written a code that validates user input and inserts data in MYSQL.

But mine is not storing and also it shows this message even if I enter all required fields. Here is my code:

***** Please use the

Code: Select all

tag when posting code *****[/color]

Code: Select all

<?php
$db = mysql_connect(localhost, 'db_username', 'db_password') or die('Error: ' . mysql_error());
mysql_select_db('dbname') or die('Could not select database');
$firstname = $_POST['firstname'];  
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['passowrd'];
$str = $_POST['street'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email']; 
if ((!empty($_POST['firstname'])) && (!empty($_POST['lastname']))){ 
$firstname = "firstname; $_POST[firstname]";
$lastname = "lastname; $_POST[lastname]";
}else { 
echo "Please enter your firstname and lastname in the fields provided<br/>";
}
if((!empty($_POST['username'])) && ((!strlen($_POST['username'] < 6)) && (!strlen($_POST['username'] > 32)))){
$sql = "SELECT * FROM Accounts WHERE Username='$username'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) < 1) 
{$username = "username; $_POST[username]";
}else{
$username = NULL;
echo "Username already exists. Please enter a different username.<br/>";    
}
}
if((!empty($_POST['password'])) && ((!strlen($_POST['password'] < 6)) && (!strlen($_POST['password'] > 32)))){
$password = "password; $_POST[password]";
}else{
$password = NULL;
echo "Please enter a valid alphanumeric password that is atleast 6 characters long.<br/>";    
}
if(!empty($_POST['street'])){
$str = "street; $_POST[street]";
}else{
$str= NULL;
echo "Please enter a valid Street name.<br/>";    
}
if(!empty($_POST['city'])){
$city = "City; $_POST[city]";
}else{
$city = NULL;
echo "Please enter a valid City name.<br/>";    
}
if(!empty($_POST['state'])){
$state = "State; $_POST[State]";
}else{
$state = NULL;
echo "Please select a state from the drop down menu name.<br/>";    
}
if (preg_match("/^[0-9]{5}([0-9]{4})?$/i", $zipcode)) {
$zipcode = "zipcode; $_POST[zipcode]";
} else {
$zipcode = NULL;
echo "Zip Code is invalid.<br/>";
}
if (preg_match("/^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}?$/i", $phone)) {
$phone = "phone; $_POST[phone]";
} else {
$phone = NULL;    
echo "Please enter a valid phone number.<br/>";
}
if(preg_match("/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}?$/i",$email)){ 
$email = "email; $_POST[email]"; 
} else {
$email = NULL;
echo "Please enter a valid E-Mail address.<br/>";
}
mysql_query("INSERT INTO Accounts (Firstname, Lastname, Username, Password, Street, City, State, Zipcode, Primary Phone, Email) VALUES ('$firstname', '$lastname', '$username', '$password', '$str', '$city', '$state', '$zipcode', '$phone', '$email'))"); 
?>
It throws this message:
Please enter a valid alphanumeric password that is atleast 6 characters long.
Please enter a valid Street name.
Please enter a valid City name.
Please select a state from the drop down menu name.

Thank you so much.
Priya

Re: Help Needed- user Input Validation

Posted: Fri May 01, 2009 9:57 pm
by requinix
The first one is easy:

Code: Select all

if((!empty($_POST['password'])) && ((!strlen($_POST['password'] < 6)) && (!strlen($_POST['password'] > 32)))){

Code: Select all

!strlen($_POST['password'] < 6)
!strlen($_POST['password'] > 32)
Look hard at that.


For the others, what data are you trying to submit?

Re: Help Needed- user Input Validation

Posted: Sat May 02, 2009 12:39 pm
by phphelpseeker
Thank you for replying. I'm trying to validate firstname, lastname, username, password, street, city, state, zipcode, phone and e-mail entered through a form. After successful validation, these values should be inserted into MySql database all at once.

But it is not validating anything except firstname and lastname. Also the values are not stored in the database.

Can anybody point out whats wrong in my code, please?

Regarding the reply, mine also looks the same. I don't get the suggestion. Please clarify.

Thank you.
Priya

Re: Help Needed- user Input Validation

Posted: Sat May 02, 2009 1:53 pm
by joshmaker

Code: Select all

!strlen($_POST['password'] < 6)
Should be:

Code: Select all

!strlen($_POST['password']) < 6
also for security reasons you NEVER want to enter directly enter user submitted values into a MySQL database without checking it for SQL injection attacks. http://www.tizag.com/mysqlTutorial/mysq ... ection.php

So,

Code: Select all

$sql = "SELECT * FROM Accounts WHERE Username='$username'";
$query = mysql_query($sql) or die(mysql_error());
should be

Code: Select all

$sql = "SELECT * FROM Accounts WHERE Username='mysql_real_escape_strings($username)'";
$query = mysql_query($sql) or die(mysql_error());
Tasks like data validation and database insertions can be made much quicker and easier through the use of a PHP Framework or a good set of re-usable helper functions. However, it is important to learn how things are done directly before trying to farm the work out to an external library.

Re: Help Needed- user Input Validation

Posted: Sat May 02, 2009 7:29 pm
by phphelpseeker
Thank you so much for clarifying. I'm really new to PHP. Can anybody please check my street, city, state, zipcode, phone and email validations as well. They are not throwing any errors. I entered all the fields. After I click submit, it asks me enter valid street, city,......... I don't know what is wrong with my code. Can anyone please help me?


Priya

Re: Help Needed- user Input Validation

Posted: Sun May 03, 2009 12:36 am
by McInfo
joshmaker wrote:Should be:

Code: Select all

!strlen($_POST['password']) < 6
Actually, that statement compares "not string length" to 6. String length is an integer and "not integer" is false (as long as the integer is not 0). False is always less than 6, so the entire statement is true for any string one character or longer. The only time the statement is false is when the string length is zero.

Code: Select all

var_dump(!strlen('a') < 6); // bool(true)
var_dump(!strlen('abcdefghijklmnop') < 6); // bool(true)
var_dump(!strlen('') < 6); // bool(false)
One correct statement is the following. There is a little trick in it. The password length variable ($pl) is declared inline, then used in the next comparison. This avoids calling strlen() twice. Or you could call strlen() twice.

Code: Select all

if (isset($_POST['password']) && 5 < ($pl = strlen($_POST['password'])) && $pl < 33)
The next example is also valid, as are other variants of these two examples. The strlen() requirements ensure that the password is not "empty" so isset() can be used instead of empty().

Code: Select all

if (isset($_POST['password']) && strlen($_POST['password']) >= 6 && strlen($_POST['password']) <= 32)
Edit: This post was recovered from search engine cache.

Re: Help Needed- user Input Validation

Posted: Sun May 03, 2009 5:14 pm
by phphelpseeker
Thank you so much. What about other validations? Can you please verify? Also the data is not getting inserted in the table. Is my INSERT statement worng? I have been trying hard for the past 2 days. Please help me.

Priya

Re: Help Needed- user Input Validation

Posted: Sun May 03, 2009 7:20 pm
by McInfo
Problems with your code...
  • Line 2: localhost is a constant. It is converted to a string because PHP cannot find a defined constant named "localhost". This is a side-effect that should not be relied on.
  • Lines 3-13: The values of the POST variables are passed to local variables, but the POST variables are still used beyond line 13.
  • Have you verified that $_POST actually contains what you think it does? (Use print_r() or var_dump())
  • Lines 15-16, 24, ..., 67: Array indexes without quotes
  • Lines 20, 30: Illogical control statements that have been the subject of most of the discussion so far
  • Line 21: If the only purpose of the query is to check if a username exists, perhaps "SELECT Username FROM..." would be a better query.
  • Line 49: Strings are case sensitive, including array indexes. On line 10, "state" was lowercase. On line 49, "State" is capitalized.
  • In general: Lack of formatting
Edit: This post was recovered from search engine cache.

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 8:16 am
by phphelpseeker
Thank you. So what would be correct logical statements (Lines 20 & 30). Any suggestons? Can anybody please check my query to insert data into DB?

Thank you.
phphelpseeker

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 9:03 am
by phphelpseeker
Can anyone please check my insert statement?

Code: Select all

$sqli = "INSERT INTO Accounts (Firstname, Lastname, Username, Password, Street, City, State, Zipcode, Primary Phone, Email) VALUES ('$firstname', '$lastname', '$username', '$password', '$str', '$city', '$state', '$zipcode', '$phone', '$email')"; 
$ins = mysql_query($sqli) or die(mysql_error());
 
It thorws the following error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Primary Phone, Email) VALUES ('', '', '', '', '', '', '', '', '', '')' at line 1

Please help me.
Priya

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 9:08 am
by phphelpseeker
My php code starts directly with <?php>
Should it start with something else?

I'm really new to this one? please help me.

Thank you.
Priya

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 9:50 am
by phphelpseeker
Thank you all for helping me. I found the mistake in my query. Its working now.

Priya

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 11:39 am
by phphelpseeker
I'm using the following code to check username. If it already exixts, it should display, "Username exists. Please try a different one."
But mine is just dispalying, "Duplicate entry on key 2". Also I can see only first three digits of the phone number the user enters. Everything else is working fine. Thank you all for helping me. Please .....please help me figure out the above problems as well. I haven't included the DB connection part.

Priya
Here is my code:

Code: Select all

 
 
$firstname = $_POST['firstname'];  
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['passowrd'];
$str = $_POST['street'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email']; 
if ((isset($_POST['firstname'])) && (isset($_POST['lastname']))){ 
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
}else { 
echo "Please enter your firstname and lastname in the fields provided<br/>";
}
if(isset($_POST['username']) && strlen($_POST['username']) >= 6 && strlen($_POST['username']) <=32){
$sql = "SELECT * FROM Accounts WHERE Username='mysql_real_escape_strings($username)'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) < 1) 
{$username = $_POST['username'];
}else{
$username = NULL;
echo "Username already exists. Please enter a different username.<br/>";    
}
}
if(isset($_POST['password']) && strlen($_POST['password']) >= 6 && strlen($_POST['password']) <= 32 ){
$password = md5($_POST['password']);
}else{
$password = NULL;
echo "Please enter a valid alphanumeric password that is atleast 6 characters long.<br/>";    
}
if(isset($_POST['street'])){
$str = $_POST['street'];
}else{
$street = NULL;
echo "Please enter a valid Street name.<br/>";    
}
if(isset($_POST['city'])){
$city = $_POST['city'];
}else{
$city = NULL;
echo "Please enter a valid City name.<br/>";    
}
if(isset($_POST['state'])){
$state =  $_POST['state'];
}else{
$state = NULL;
echo "Please select a state from the drop down menu name.<br/>";    
}
if (preg_match("/^[0-9]{5}([0-9]{4})?$/i", $zipcode)) {
$zipcode = $_POST['zipcode'];
} else {
$zipcode = NULL;
echo "Zip Code is invalid.<br/>";
}
if (preg_match("/^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}?$/i", $phone)) {
$phone = $_POST['phone'];
} else {
$phone = NULL;    
echo "Please enter a valid phone number.<br/>";
}
if(preg_match("/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}?$/i",$email)){ 
$email = $_POST['email']; 
} else {
$email = NULL;
echo "Please enter a valid E-Mail address.<br/>";
}
$sqli = "INSERT INTO Accounts (Firstname, Lastname, Username, Password, Street, City, State, Zipcode, `Primary Phone`, Email) VALUES ('$firstname', '$lastname', '$username', '$password', '$str', '$city', '$state', '$zipcode', '$phone', '$email')"; 
$ins = mysql_query($sqli) or die(mysql_error());
?>
 

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 1:21 pm
by phphelpseeker
Can anybody correct my phone validation? If I include "-"(hyphen), only the first three digits are stored in DB. If I don't include hyphen, all users have the same number stored in DB. Please correct my code. This is very inportant to me. please help me.

Code: Select all

 
if(ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', $phone)) {
} else {
$phone = NULL;    
echo "Please enter a valid phone number.<br/>";
 
Priya

Re: Help Needed- user Input Validation

Posted: Mon May 04, 2009 1:35 pm
by McInfo
One way to validate a phone number is to strip out every character that is not a digit, then make sure the remaining string is seven, ten, or eleven characters long (at least in the United States).

Some examples:
  1. "1 (234) 567-8901" becomes "12345678901"
  2. "34.567.8901" becomes "345678901"
  3. "5#6/7!8+9/0Q1" becomes "5678901"
A and C are valid, but B is not valid because it is nine characters long.

Edit: This post was recovered from search engine cache.