How should I validate form input data using PHP? [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Hi im still learning PHP so dont be too harsh if my code seems stupid. Anyways, I'm trying to make a contact page and add validation to it. I'm using an if statement but I don't think it is right, any way how should the below code look?
<?php
if($name_blank == false){
echo"you left name blank";
}
else if($email_blank == false){
echo"Email blank";
}
else if($email_fake == false){
echo"Fake email";
}
else if($number_blank == false){
echo"Number blank";
}
else if($number_low == false){
echo"Number incorrect";
}
else if($number_fake == false){
echo"Fake number";
}
else if($comment_blank == false){
echo"Commant blank";
}else{
hasError = false;
}
?>
thanks.

There are plenty of libraries/frameworks that will take care of most of the work involved in forms (and other annoying bits in PHP) for you. I like Symfony but you might want to find something a bit less complicated if all you want is a contact form.
Both IF/ELSEIF/ELSE and SWITCH/CASE aren't great structures for something like this. In both cases, the code will stop at the first condition that evaluates to true. If someone has more than one invalid input in your form, you will only output an error message for the first issue you find.
I would use something like:
$hasError = false;
if($name_blank == false){
echo"you left name blank";
$hasError = true;
}
if($email_blank == false){
echo"Email blank";
$hasError = true;
}
if($email_fake == false){
echo"Fake email";
$hasError = true;
}
if($number_blank == false){
echo"Number blank";
$hasError = true;
}
if($number_low == false){
echo"Number incorrect";
$hasError = true;
}
if($number_fake == false){
echo"Fake number";
$hasError = true;
}
if($comment_blank == false){
echo"Commant blank";
$hasError = true;
}
Of course, there is a lot more to properly using forms, but to get the basic functionality your looking for, this will do the job.

Considering usage of else if it seems all right.
In PHP, you can write both elseif or 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different but the bottom line is that both would result in exactly the same behavior.

some short stuff:
instead of writing ($a == false), you can always write (!$a)
if name_blank indicates that the name is blank, one would think that an error message is in order if it true, not false, so maybe your variable naming is a bit strange
no reason not to give out all the errors, not only the first one (ie only if (){} if (){} etc.) you might want to add them to an error message string, that will also allow you to find out if hasError or not

Please look into these functions:
empty() - helps to check whether the user submitted data into a field
strip_tags() - prevents XSS*
isset() - check whether a variable is set or not
And when you'll start learning databases:
mysqli_real_escape_string() - prevents SQL injection*
What you did there is not enough, nor correct.
If the name is NOT blank then you skip every other field, because of else if's, but those skipped fields could be empty, too!
So I recommend you understand the execution flow first, in this case having only ifs it would be ok, plus the functions I mentioned above!
* of course there is more you can do, but for now it's enough

Do all the user friendly validation on client side and ignore requests coming with an invalid form data on the server side for security.
Somebody who passes through your client side validation doesn't deserve any user friendliness anyway.
Validation is too expensive in terms of programmer time. Don't spend too much time on validating input.
in this case, use ifs and not else ifs, learn what if and else does.
My personal preference is
switch(true){
case blabla>number: break;
case blabla=="": break;
case strlen(blabla)==5: break;
}

Related

Simple password validation in PHP

I'm a beginner to PHP trying to learn the basics of validating form data. I want to check if the password has been set, and if it has then to further check if it is the right length and has the right characters etc.
//check if set
if (empty($_POST['password']) {
//further validate - check length, characters etc
if (myFunction(($_POST['password'])) {
//success
$password = $_POST['password'];
}
else {
$error = "Password must be at least 8 characters and contain at least one number";
}
}
else {
$error = "Password is required";
}
The problem I'm having is if the user enters "0" as a password, the empty() function treats this as empty, and they're given the "Password is required" error, rather than the "Password must have..." etc error.
Using the isset() function instead wouldn't work either because an empty field would return an empty string, which would be considered to be set.
At the moment I have a workaround where I have a further conditional to check if the password is set to "0", but there must be a more elegant way.
Apologies if this has been covered in another question, I couldn't find anything. Thanks
Use isset() (and possibly strlen(trim()), not empty(). Although the way this code is shown, it will process only an empty password, and give an error to anyone who puts in a password.
if(isset($_POST['password']) && strlen(trim($_POST['password']))){
//process
}else{
//error
}
If you are just learning the basics, then use the function below. However, do remember in a live environment you will want to be hashing passwords properly. Read this link for more info: http://php.net/manual/en/faq.passwords.php
function PasswordCheck($password_string)
{
$password_string = trim($password_string);
if($password_string == '')
{
die("Password not entered");
}
elseif(strlen($password_string) < 8)
{
die("Password must be more than 8 characters in length");
}
elseif(!(preg_match('#[0-9]#', $password_string)))
{
die("Password must contain at least one number");
}
else
{
//Success, now process password
}
}
$password = $_POST['password'];
PasswordCheck($password);
You can use is_null() function or:
if ($_POST['password']==NULL)
please don't forget to use htmlspecialchars once before you use $_POST to make sure no XSS scripting attacK.
Isset function is better than empty in your case.
Additonally if you want user to get at least 8 characters and contain one number, use regular expression it is much better.
0 is considered to be empty in php. (source: http://php.net/empty )
You could get around this by checking if it is empty or if there is nothing in the string, or if it is exactly null, like so:
if ((empty($_POST['password']) || ($_POST['password']=='') ||
($_POST['password']===null) ) {
...
}
This should cover all your bases, however it is easy to check that something is there than checking a negative (I find it cognitively easier), such as making sure the password is entered, instead of checking to see whether it is not entered
The 'PHP Type Comparison Table' is your friend.
http://php.net/manual/en/types.comparisons.php
To check if the password has been set.
// Check if it has been set and contains characters.
if (isset($_POST['password']) && strlen($_POST['password']) > 0)
{
// Passed, now check for the right length, characters, etc.
if (myFunction(($_POST['password']))
{
// Success.
$password = $_POST['password'];
} else {
// Error.
$error = "Password must be at least 8 characters and contain at least one number";
}
} else {
// Failed.
$error = "Password is required";
}
If you require help with your 'myFunction()' function to check length, characters, etc then you will need to post that code as well.
Hope this helps.

Stuck Troubleshooting Compound IF Statement

I am experienced programmer, but am not a PHP developer. I have been asked to troubleshoot the following code, but can't see what the problem is. This IF statement works:
<?php
if ($ice_cream_social == 'yes') {
$registration_price = "58.00";
}
?>
However, the page in question requires some compound IF statements to test if form elements have been checked and adjust the price accordingly. This code does NOT work, it doesn't give an error -- but the IF doesn't execute:
<?php
if ($ice_cream_social == 'yes' AND $registration_type == 'Banquet and Conference') {
$registration_price = "78.00";
?>
Using developer tools I have verified the form fields are being passed from the HTML, the code has the variable name and value spelled correctly, and I can test for any ONE variable's value successfully. It seems that when a second or third test is added using the syntax I showed above, the test fails and the IF doesn't run. Based on my limited understanding of PHP's syntax and some Googling, the code looks correct to me (and does not produce any errors), but I am thinking I am missing something about why this isn't working.
Can someone tell me if I'm missing something obvious in my code sample that would cause the IF not to run? I didn't include more code as this is one piece of a messy set of includes :)
Thanks!
It looks like to me on the elseif you don't have a logical check, so you either need to change it to else or add a check(if that is your intention) elseif($registration_price>0)
I used this code to test:
<?php
$registration_price = '';
$ice_cream_social = 'yes';
//$ice_cream_social = 'no';
$registration_type = 'Banquet and Conference';
//$registration_type = 'Something else';
if ($ice_cream_social == 'yes') {
$registration_price = "58.00";
} else {
$registration_price = "not defined";
}
echo $registration_price;
if ($ice_cream_social == 'yes' && $registration_type == 'Banquet and Conference') {
$registration_price = "78.00";
} elseif( 1 > 0) {
$registration_price = "1 million dolars!";
} else {
$registration_price = "not defined";
}
echo $registration_price;

check string function

I am currently trying to get my head around some basic php string functions. I currently use this code which determines if the username entered in long enough e.g.:
if (strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
And this works just fine. Which string function should I use though if I want to to check on a specific name? E.g. I would like to trigger a message once someone enters a specific Word in the form field.
Some expert advice would be greatly appreciated.
This link of 60 PHP validation functions is an excelent resource.
For your case as to check a name, you could use something like:
if (strtolower($_GET['name']) === 'joe') {
// Do something for Joe
}
elseif (in_array(strtolower($_GET['name']), array('dave', 'bob', 'jane')) {
// Do something else for Dave, Bob or Jane
}
The strtolower will ensure that upper, lower or mixed case names will match.
You don't need a function for that. You can use a if statement and ==:
if ( $_GET['name'] == 'Dave' )
{
// user entered 'Dave'
}
if statement, or if you plan to check against multiple names, switch().
switch($_GET['name']){
case "Eric":
//Eric
break;
case "Sally":
//Sally
break;
case "Tom":
//Tom
break;
default:
//Unknown
}
Its good practice to check that $_GET['name'] is set before using. To answer your question a good way IMO is in_array(needle,haystack)
<?php
if (!empty($_GET['name']) && strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
//From a database or preset
$names = array('Bob','Steve','Grant');
if(in_array($_GET['name'], $names)){
echo 'Name is already taken!';
exit;
}
?>
You can use strstr or stristr(case-insensitive) function, If want to search for specific word in a sentence.
Just check php mannual for strstr, and stristr.

PHP - Wondering about efficiency of nested IF statements for user registration

I am working on a little project of designing a website for my friends and myself.
I am currently building the user registration system and am wondering if the way I am checking user's entries is the best it could be.
Um, ignore the api stuff, it is for eve and likely irrelevant.
I have plans for the elses.
Essentially, I would like to know if this is acceptable in terms of... everything.
And if not, what could I do to improve this.
I am newer to PHP, please be kind :)
So, this is what I am currently using:
if (!empty($_POST['username'])
&& !empty($_POST['password1'])
&& !empty($_POST['password2'])
&& !empty($_POST['email1'])
&& !empty($_POST['email2'])
&& !empty($_POST['keyID'])
&& !empty($_POST['vCode'])
){
$api = new EVEAPI();
if ($api->getCharacterID($_POST['username']) != 0){
//The username is valid.
if ($_POST['password1'] == $_POST['password2']){
//Passwords match.
if ($_POST['email1'] == $_POST['email2']
&& filter_var($_POST['email1'], FILTER_VALIDATE_EMAIL)
){
//Emails match and are in valid format.
if ($api->isValidAPI($_POST['keyID'], $_POST['vCode'])){
//If the API returns something that is not an error, continue.
$xml = $api->getAPIKeyInfo($_POST['keyID'], $_POST['vCode']);
if ($xml->result->key->attributes()->type == 'Account'){
//If the 'type' of the returned API info is 'Account', continue.
foreach ($xml->result->key->rowset->row as $apiRow){
$charID = (int) $apiRow->attributes()->characterID;
if ($charID == $api->getCharacterID($_POST['username'])){
//DO SOMETHING WITH INFO
}
else{
}
}
}
else{
}
}
else{
}
}
else{
}
}
else{
}
}
else{
}
Efficiency wise this isn't going to matter all that much, but for maintainability's sake it will.
Instead of nesting so many ifs like that, try early failure with your ifs. Something like this:
if ($api->getCharacterID($_POST['username']) == 0) {
// Fail early. Throw an exception, die, or whatever
}
// Continue along as normal, not in an else.
if ($_POST['email1'] != $_POST['email2']) {
// Fail early. Throw an exception, die, or whatever
}
// Etc.
That sort of strategy will generally serve you well unless there's a very good reason to not use it.
It is hard to read and not very clean. The way I do it is use negative if statements. By that I mean the following:
if ($api->getCharacterID($_POST['username']) == 0){
// Username is not valid, so stop execution
}
if ($_POST['password1'] != $_POST['password2']) {
// Send error to user and stop execution
}
// ...etc.
Now how do you stop execution? Well you have few options
Throw an exception
Use die statement
have a parameter that you change everytime you enter an if block, then check if you should continue.
some other solution
But the point is, this approache makes your code cleaner.
Cheers.
These days mostly programmer use jquery / Javascript for forms validations, but if you are using pure PHP the try below code, hope it will be good and secure obviously :)
$username = mysql_real_escape_string($_POST['username']);
if($username == "")
{
$username_required = '<div>Please enter your username</div>';
} else {
$username_ok = true;
}
Typically in most validation patterns out there they have this errors array where you check for all the conditions and add error messages into the array if the array is empty at the end it only means that there are no errors..
For me i wouldn't want my code to look too nested like this i would use variables to dictate each step.
From there you can decide whether to display just the first error. It doesnt hurt to validate through everything at once because the processing should not be that extensive unless you have like 5000 form fields. I think it's ok.
When you code you must remember because code is written for humans and you will want to be kind to your eyes or for those who read your code.. Basically nested is ok. it saves some further processing and it also depends on the logic you need.
Yes its good to save time but at times you do things too nicely to minimize processing you have to weigh the needs if you do it so nice but in the end the time you save is so substantial then it makes no point.. The compiler is not going to pat your back and say good job anyways..
$errors = array();
$usernameValid = $api->getCharacterID($_POST['username']) != 0;
if (!$usernameValid) $errors[] = 'Username is not valid';
//If you want to store which attribute caused the error you can use the attribute name as array key
//if (!$usernameValid) $errors['username'] = 'Username is not valid';
$passwordMatches = $_POST['password1'] == $_POST['password2'];
if (!$passwordMatches) $errors[] = 'Password does not match';
if ($usernameValid && $passwordMatches)
{
//What to do if user name and password passes validation. wooo hoo~
}
//Etc etc..

preg_match multiple expressions

hi guys i was wondering how could i build e regExp that says:
"this string may contain 1-25 letters that are not these specific words:"root","bin","download","shutdown"
So I thought:
$dang_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,$field) || !preg_match($dang_words,$field))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
But it's not working
why?
thanks
Luca
$dangerous_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,strtolower(trim($field))) && !preg_match($dangerous_words,strtolower(trim($field))))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
You have your logical operators messed up.. Just changed from || to &&.
Close... Try this:
/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/
It uses a forward assertion
So, it becomes:
if (preg_match('/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/', $content)) {
echo "Your input is ok";
} else {
echo "there is a bad word/invalid content";
}
I think your issue lies with all the ( ). In some old code I created a while ago I used this:
$stopInjectionVerbs = "/(alter|begin|cast|convert|create|cursor|declare|delete|drop|end|exec|fetch|insert|kill|open|select|sys|table|update)/";
$errors = array();
if (preg_match($stopInjectionVerbs, $select)) {
$errors[] = "Can not use SQL injection Strings";
}
This all works correctly. Have a go without the brackets around each individual word.

Categories