hi can any one tell me how validation can be done in PHP WITH OUT USINGjavascript
Duplicate... The quick-reply thing keeps doing that![]()
thanks Alti.. but i didnt understand your second answer properly
// Nullify the effects of the magic_quotes feature, if enabled. // This is targeted only at the $_POST array. You can change it to $_REQUEST if needed. if(get_magic_quotes_gpc()) { foreach($_POST as &$_data) { $_data = stripslashes($_data); } }
// List all fields you are expecting to get $fields = array('username', 'email', 'password'); // Set up an array to contain all errors that occur during the validation. // This can then be used later on to determine whether or not the validation failed. $errors = array(); // Step through the list of expected fields and verify that they are set, and that they are not empty. foreach($fields as $_field) { if(!isset($_POST[$_field]) || empty($_POST[$_field])) { $errors[] = "Field '$_field' is missing or empty."; } }
// Verify the username. $usernameRegexp = '/[\w\d_-\' ]{3,32}/i'; if(!preg_match($passwordRegexp, $_POST['username'])) { $errors[] = "Usernames must be between 3 and 32 characters long, and they may only contain letters, numbers, spaces, and the following characters: (_), (-), (')."; } // Verify the password. if(strlen($_POST['password']) < 6) { $errors[] = "Passwords must be more than 6 characters"; } // Verify the email $emailRegexp = '/^([\w\d.-_]+?)@([\w\d.-_]+?)\.(\w{2,4})$/i'; if(!preg_match($emailRegexp, $_POST['email'])) { $errors[] = "The email address is invalid!"; }
$errors array to determine if the validation failed or succeeded:
// Check if there were any errors if(count($errors) == 0) { // The data is valid. // Do with it as you please. } else { // Print all the errors. echo "<p>The following errors were found:<br><ul>" foreach($errors as $_error) { echo "<li>$_error</li>"; } echo "</ul><p>"; }
// Prepare all fields for being used in a MySQL query. $safeData = array(); foreach($fields as $_field) { $safeData[$_field] = mysql_real_escape_string($_POST[$_field]); }
// Create a password hash. Never store passwords as plain text! $passwordHash = hash("sha256", $safeData['password']);
// Compile the query, using the verified data $sql = "SELECT `id` FROM `user` WHERE (`username` = '{$safeData['username']}') AND (`email` = '{$safeData['email']}') AND (`passwordHash` = '{$passwordHash}')";
// Execut the query and check the results. $result = mysql_query($sql); if($result && mysql_num_rows($result) == 1) { echo "Login succesfull!"; // And then do stuff to actually log him in. } else { echo "Login failed! Better luck next time."; }

Yes, sorry about that second post. When I posted my first post it got posted twice because of a bug in the forum. (I assume)
It has been removed now.
But OK, as form validation is a rather important topic, let me be a little more thorough.
There are a few steps that are necessary when validating incoming user data.
Put that all together and you will have a pretty decent user-login validation script.
- First step is to eliminate the possibility that the ancient magic_quotes feature is messing up your data. (Ideally, it should be turned off. But it is always best to add this just in case.)
A few simple lines of code can completely nullify that effect, if it is present.
Keep in mind that this code should only be executed once per page, or you risk messing up your data even further.
php Syntax (Toggle Plain Text)
// Nullify the effects of the magic_quotes feature, if enabled. // This is targeted only at the $_POST array. You can change it to $_REQUEST if needed. if(get_magic_quotes_gpc()) { foreach($_POST as &$_data) { $_data = stripslashes($_data); } }- Verify that all the fields you need are present and filled in.
In these examples I'll assume you want to verify user login data, where a user passes both his user-name and an email, as well as his password.
php Syntax (Toggle Plain Text)
// List all fields you are expecting to get $fields = array('username', 'email', 'password'); // Set up an array to contain all errors that occur during the validation. // This can then be used later on to determine whether or not the validation failed. $errors = array(); // Step through the list of expected fields and verify that they are set, and that they are not empty. foreach($fields as $_field) { if(!isset($_POST[$_field]) || empty($_POST[$_field])) { $errors[] = "Field '$_field' is missing or empty."; } }- Verify the data in individual fields. As opposed to the previous code example, which only verified their existence, this one verifies that the data you are receiving is in valid format.
php Syntax (Toggle Plain Text)
// Verify the username. $usernameRegexp = '/[\w\d_-\' ]{3,32}/i'; if(!preg_match($passwordRegexp, $_POST['username'])) { $errors[] = "Usernames must be between 3 and 32 characters long, and they may only contain letters, numbers, spaces, and the following characters: (_), (-), (')."; } // Verify the password. if(strlen($_POST['password']) < 6) { $errors[] = "Passwords must be more than 6 characters"; } // Verify the email $emailRegexp = '/^([\w\d.-_]+?)@([\w\d.-_]+?)\.(\w{2,4})$/i'; if(!preg_match($emailRegexp, $_POST['email'])) { $errors[] = "The email address is invalid!"; }- And finally, use the
$errorsarray to determine if the validation failed or succeeded:
php Syntax (Toggle Plain Text)
// Check if there were any errors if(count($errors) == 0) { // The data is valid. // Do with it as you please. } else { // Print all the errors. echo "<p>The following errors were found:<br><ul>" foreach($errors as $_error) { echo "<li>$_error</li>"; } echo "</ul><p>"; }
Also, while I'm at it. If you were planing on using the data in that form to log a user in via a SQL query, further security measures need to be taken.
- One of the biggest threat to PHP security is SQL Injection.
This is what the now deprecated magic_quotes feature was meant to prevent, but it was only ever partially effective, and it causes far to much trouble to be wort using.
There are several ways to prevent this, most of them database-specific. MySQL databases, for example, have the mysql_real_escape_string function, which takes care of escaping the data for you.
You could use that on the data in the previous examples like so:
php Syntax (Toggle Plain Text)
// Prepare all fields for being used in a MySQL query. $safeData = array(); foreach($fields as $_field) { $safeData[$_field] = mysql_real_escape_string($_POST[$_field]); }- Hash your passwords!
A basic way to protect your user's passwords from being known by others, including you, is to use a one-way encryption algorithm on it, known as "hashing", to turn it into a long string of seemingly random characters.
Then you store the hash in the database as the user's password. When it comes time to log the user in, you hash the password he provides in the same way you did when it was created, and compare the two. If the hashes match, it is valid.
php Syntax (Toggle Plain Text)
// Create a password hash. Never store passwords as plain text! $passwordHash = hash("sha256", $safeData['password']);- And then you create and execute the query, using the now secure data.
php Syntax (Toggle Plain Text)
// Compile the query, using the verified data $sql = "SELECT `id` FROM `user` WHERE (`username` = '{$safeData['username']}') AND (`email` = '{$safeData['email']}') AND (`passwordHash` = '{$passwordHash}')";- Which you would finish of like so:
php Syntax (Toggle Plain Text)
// Execut the query and check the results. $result = mysql_query($sql); if($result && mysql_num_rows($result) == 1) { echo "Login succesfull!"; // And then do stuff to actually log him in. } else { echo "Login failed! Better luck next time."; }
I'll leave it there... for now![]()
Yes, sorry about that second post. When I posted my first post it got posted twice because of a bug in the forum. (I assume)
It has been removed now.
But OK, as form validation is a rather important topic, let me be a little more thorough.
There are a few steps that are necessary when validating incoming user data.
Put that all together and you will have a pretty decent user-login validation script.
- First step is to eliminate the possibility that the ancient magic_quotes feature is messing up your data. (Ideally, it should be turned off. But it is always best to add this just in case.)
A few simple lines of code can completely nullify that effect, if it is present.
Keep in mind that this code should only be executed once per page, or you risk messing up your data even further.
php Syntax (Toggle Plain Text)
// Nullify the effects of the magic_quotes feature, if enabled. // This is targeted only at the $_POST array. You can change it to $_REQUEST if needed. if(get_magic_quotes_gpc()) { foreach($_POST as &$_data) { $_data = stripslashes($_data); } }- Verify that all the fields you need are present and filled in.
In these examples I'll assume you want to verify user login data, where a user passes both his user-name and an email, as well as his password.
php Syntax (Toggle Plain Text)
// List all fields you are expecting to get $fields = array('username', 'email', 'password'); // Set up an array to contain all errors that occur during the validation. // This can then be used later on to determine whether or not the validation failed. $errors = array(); // Step through the list of expected fields and verify that they are set, and that they are not empty. foreach($fields as $_field) { if(!isset($_POST[$_field]) || empty($_POST[$_field])) { $errors[] = "Field '$_field' is missing or empty."; } }- Verify the data in individual fields. As opposed to the previous code example, which only verified their existence, this one verifies that the data you are receiving is in valid format.
php Syntax (Toggle Plain Text)
// Verify the username. $usernameRegexp = '/[\w\d_-\' ]{3,32}/i'; if(!preg_match($passwordRegexp, $_POST['username'])) { $errors[] = "Usernames must be between 3 and 32 characters long, and they may only contain letters, numbers, spaces, and the following characters: (_), (-), (')."; } // Verify the password. if(strlen($_POST['password']) < 6) { $errors[] = "Passwords must be more than 6 characters"; } // Verify the email $emailRegexp = '/^([\w\d.-_]+?)@([\w\d.-_]+?)\.(\w{2,4})$/i'; if(!preg_match($emailRegexp, $_POST['email'])) { $errors[] = "The email address is invalid!"; }- And finally, use the
$errorsarray to determine if the validation failed or succeeded:
php Syntax (Toggle Plain Text)
// Check if there were any errors if(count($errors) == 0) { // The data is valid. // Do with it as you please. } else { // Print all the errors. echo "<p>The following errors were found:<br><ul>" foreach($errors as $_error) { echo "<li>$_error</li>"; } echo "</ul><p>"; }
Also, while I'm at it. If you were planing on using the data in that form to log a user in via a SQL query, further security measures need to be taken.
- One of the biggest threat to PHP security is SQL Injection.
This is what the now deprecated magic_quotes feature was meant to prevent, but it was only ever partially effective, and it causes far to much trouble to be wort using.
There are several ways to prevent this, most of them database-specific. MySQL databases, for example, have the mysql_real_escape_string function, which takes care of escaping the data for you.
You could use that on the data in the previous examples like so:
php Syntax (Toggle Plain Text)
// Prepare all fields for being used in a MySQL query. $safeData = array(); foreach($fields as $_field) { $safeData[$_field] = mysql_real_escape_string($_POST[$_field]); }- Hash your passwords!
A basic way to protect your user's passwords from being known by others, including you, is to use a one-way encryption algorithm on it, known as "hashing", to turn it into a long string of seemingly random characters.
Then you store the hash in the database as the user's password. When it comes time to log the user in, you hash the password he provides in the same way you did when it was created, and compare the two. If the hashes match, it is valid.
php Syntax (Toggle Plain Text)
// Create a password hash. Never store passwords as plain text! $passwordHash = hash("sha256", $safeData['password']);- And then you create and execute the query, using the now secure data.
php Syntax (Toggle Plain Text)
// Compile the query, using the verified data $sql = "SELECT `id` FROM `user` WHERE (`username` = '{$safeData['username']}') AND (`email` = '{$safeData['email']}') AND (`passwordHash` = '{$passwordHash}')";- Which you would finish of like so:
php Syntax (Toggle Plain Text)
// Execut the query and check the results. $result = mysql_query($sql); if($result && mysql_num_rows($result) == 1) { echo "Login succesfull!"; // And then do stuff to actually log him in. } else { echo "Login failed! Better luck next time."; }
I'll leave it there... for now![]()
That was nice Atli... I need to learn how to create that custom regex codes. May be a link to some tutorial can be helpful..
| DaniWeb Message | |
| Cancel Changes | |