Php validation not working. Even with good data (closed) - php

For my website i want to have registration. And everything goes well until it's time for validation. So, i have to this all in different files (validation in validation.php, registration in registration.php and registration form in registrationForm.php). In registration.php i have something like this:
<?php
session_start();
include 'validation.php';
include "mail.php";
include 'dbConnection/dbconn.php';
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$surname = $_POST['surname'];
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
//sendMail("test", "test");
if (validateName($name) && validateSurname($surname) && validateEmail($email) && validatePassword($password1) && validateUsername($username) && checkIfPasswordsAreMatching($password1, $password2)) {
echo "Worked";
} else {
echo "Not worked";
header("Location: registrationForm.php");
}
} else {
header("Location: registrationForm.php");
}
?>
And my problem is that no matter if i put good data or completely wrong data my validation always says that it's wrong.
Here is my validation code (validation.php):
<?php
session_start();
$allChecked = true;
function validateName($string) {
if (strlen($string) < 2) {
$allChecked = false;
$_SESSION['nameError'] = "Your name is too short. It has to be at least 2 characters long.";
}
if (preg_match('[\W]', $string)) {
$allChecked = false;
$_SESSION['nameError'] = "Your name cannot contain any special character.";
}
return $string;
}
function validatePassword($string) {
if (strlen($string) < 8 || strlen($string) > 20) {
$allChecked = false;
$_SESSION['passwordError'] = "Your password must be between 8 and 20 characters long.";
}
if (preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]/', $string) == false) {
$allChecked = false;
$_SESSION['passwordError'] = "Your password must contain at least 1 big letter, 1 special character, 1 number and 1 small letter.";
}
return $string;
}
function validateSurname($string) {
if (strlen($string) < 2) {
$allChecked = false;
$_SESSION['surnameError'] = "Your surname is too short. It has to be at least 2 characters long.";
}
if (preg_match('[\W]', $string)) {
$allChecked = false;
$_SESSION['surnameError'] = "Your surname cannot contain any special character.";
}
return $string;
}
function validateUsername($string) {
if (strlen($string) < 2 || strlen($string) > 20) {
$allChecked = false;
$_SESSION['usernameError'] = "Your username must be between 2 and 20 characters";
}
/*
$sql = "SELECT * FROM Users WHERE username = '$string'";
$sql = $conn->query($sql);
$nameExists = $result->fetch();
if($nameExists) {
$allChecked = false;
$_SESSION['usernameError'] = "Name is already taken";
}
*/
return $string;
}
function validateEmail($string) {
$em = filter_var($string, FILTER_VALIDATE_EMAIL);
if (!$em){
$allChecked = false;
$_SESSION['emailError'] = "Your email has to be valid.";
}
/*
$sql = "SELECT * FROM Users WHERE mail = '$string'";
$result = $conn->query($sql);
$emailExists = $result->fetch();
if($emailExists) {
$allChecked = false;
$_SESSION['emailError'] = "Email is already taken";
}
*/
return $allChecked;
}
function checkIfPasswordsAreMatching($password1, $password2) {
if ($password2 != $password1) {
$allChecked = false;
$_SESSION['passwordError'] = "Passwords must be the same";
}
return $allChecked;
}
?>

In each of your return statements check $allChecked and if it has NOT been set return true instead of $allChecked.
return (isset($allChecked) ? $allChecked : true);

In your functions validateName, validateSurname, validatePassword, validateUsername you are returning the original string instead of validation result. In validateEmail and checkIfPasswordsAreMatching you are returning $allChecked but it's not initialized with value if all checks are passed so null is returned instead.
You should rewrite your validation functions to look like this
function validateName($string) {
if (strlen($string) < 2) {
$_SESSION['nameError'] = "Your name is too short. It has to be at least 2 characters long.";
return false;
}
if (preg_match('[\W]', $string)) {
$_SESSION['nameError'] = "Your name cannot contain any special character.";
return false;
}
return true;
}

Related

how to validate one variable either of two variables in php

i have two variables mobile and email now i want to validate both but i want the user to leave blank one of the fields if user does not have one for ex if a user does not want to register with his email then he can go to mobile number for registration and vice versa this is my validation code
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$mobileerror = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$mobile = strip_tags($_POST['mobile']);
$fullname_valid = $email_valid = $mobile_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
if ($mobile) {
$query4 = "SELECT mobile FROM users WHERE mobile = '$mobile'";
$fire4 = mysqli_query($con, $query4) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire4) > 0) {
$mobileerror = "is already taken please try another one<br> ";
} else {
$mobile_valid = true;
}
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && ($email_valid || $mobile_valid )&& $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs how to solve this problem
Use one more flag
$isValid_email_mobile = FALSE;
When control flow enters into if (filter_var($email, FILTER_VALIDATE_EMAIL)) then on SUCCESS just set $isValid_email_mobile = TRUE; It will be same if control enters in condition if ($mobile) again on SUCCESS , set it as $isValid_email_mobile = TRUE;
When $isValid_email_mobile = FALSE; becomes TRUE then you know that of the field/variable has passed your requirement and its ready for DB INSERT
Then
In your last IF condition when you try to INSERT just change IF condition to the following
IF ($fullname_valid && $isValid_email_mobile && $password_valid && $username_valid)
One more thing whenever you are using Flag logic always set your flag to some default value before using it.
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs
you have:
if (!empty($fullname)) {}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {}
if ($mobile) {}
if (!empty($username)) {}
if (!empty($password)) {}
To remove the error, try adding
if (!empty($mobile)) {
Also, I would suggest to wrap the statements a bit more. You only need one to fail in order to stop input. You could do something like this:
$mobileOrEmail = false;
if (!empty($fullname) && !empty($username) && !empty($password) {
//check fullname, username and password
if (!empty($mobile) {
//check mobile, if it passes
$mobileOrEmail = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//check email, if it passes
$mobileOrEmail = true;
}
if (!$mobileOrEmail) $errors++;
} else {
//missing input values
$errors++;
}
Personally, I would create a function for each input field.
function checkUsername($username){
//check username
return true;
}
function checkEmail($email) {
//check email
return true;
}
....
then you can run
if (checkUsername($username) && checkPassword($password)
&& checkFullname($fullname) && (checkEmail($email) || checkEmail($email)) {
//user input correct
} else {
//user input failed
}
Just to give it more structure

PHP PDO statement that checks for existing username

currently working on an application and curious as to why my script is going to a blank page once I submit my form. It started occurring when I added a piece to my script that is supposed to go into my database that checks if a username exists and then echos a message if that is the case and echos a message if it isn't the case.
This is the code:
function validateUser() {
global $user, $userErr, $validForm;
$userErr = "";
if ($user == "") {
$userErr = "nothing entered";
$validForm = false;
}
else if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-
Z]*)*$/",$user)) {
$userErr = "invalid characters";
$validForm = false;
}
elseif (strlen($user) > 1) {
$stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
username = :username");
$stmt->bindValue(':username', $user);
$stmt->execute(array($user));
$norows = $result->fetchColumn();
if ($norows > 0 ) {
$userErr = 'Username already taken';
}
else {
$userErr='User added';
}
}
}
The bit that is giving me trouble is the last elseif statement... for some reason it hasn't been doing what it's supposed to do. I've looked at many different sources and I've tried implementing different solutions but nothing has seemed to work. This function runs when the form is submitted just incase you are wondering. Very open to any possible solutions you may have. Because I just can't get it to work... thanks!
Don't Use else if() since you are using different comparison statements. Just replace all your else if() with if() only. Then use $userErr variable to check if the inputs pass all your validations.
function validateUser() {
global $user, $userErr, $validForm;
$userErr = "";
if ($user == "") {
$userErr = "nothing entered";
$validForm = false;
}
if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/",$user)) {
$userErr = "invalid characters";
$validForm = false;
}
if (strlen($user) > 1) {
$stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
username = :username");
$stmt->bindValue(':username', $user);
$stmt->execute(array($user));
$norows = $result->fetchColumn();
if ($norows > 0 ) {
$userErr = 'Username already taken';
}
}
if($userErr == "") {
$userErr='User added';
}
}

Return only true or false (PHP)

I have this PHP code which should return only either true or false after running multiple stored functions, but unfortunately it does not work as expected.
I firstly check the email validation and return true if valid and false if invalid, then i am doing the same for username.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
I need to return only False or True after checking both.
I know that it is very small trick but i could not get it.
Try this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
} else { $valid=false; } //and between the last $valid value
}
or again this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else {
$valid=false; return} //exit from the function if valid is false
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
if(checkmail($_POST['email']) && checkuser($_POST['username'],5,10)) {
$_SESSION['v_mail'] = $_POST['email'];
$_SESSION['v_username'] = $_POST['username'];
$valid = true;
} else {
$valid = false;
}
Sorry was tired missed part of the code, however I would approach this problem little bit differently:
$isMail = (checkmail($_POST['email'])) ? $_SESSION['v_mail'] = $_POST['email'] : false;
$isUser = (checkuser($_POST['username'],5,10)) ? $_SESSION['v_username'] = $_POST['username'] : false;
$valid = $isMail && $isUser;
Or move $_SESSION variables to checkmail, checkuser functions and then simply $valid = checkmail($_POST['email']) && checkuser($_POST['username'],5,10)

Record data as array in txt file

I need to create very simple register/login system in PHP. User details must be stored in array in txt file. For some reasons even when PHP not show any error details are not saved to txt file. Any hint?
$fullname='';
$email ='';
$username ='';
$password = '';
$error = '';
$form_is_submitted = false;
$errors_detected = false;
$clean = array();
$errors = array();
if (isset($_POST['submit'])) {
$form_is_submitted = true;
if (ctype_alnum ($_POST['fullname'])) {
$clean['fullname'] = $_POST['fullname'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your Full Name!';
}
if (ctype_alnum ($_POST['email'])) {
$clean['email'] = $_POST['email'];
} else {
$errors_detected = true;
$errors[] = 'You have enter an invalid e-mail address. Please, try again!';
}
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
if ($form_is_submitted === true
&& $errors_detected === false) {
$fp = fopen('filewriting.txt', 'w');
fwrite($fp, print_r($clean, TRUE));
fclose($fp);
} else {
echo $errors;
}
There are a few things wrong with your code.
There is a missing brace for
if (isset($_POST['submit'])) {$form_is_submitted = true;
so it needs to read as
if (isset($_POST['submit'])) {
$form_is_submitted = true;
}
You are using ctype_alnum so when it comes to an email address, the # and the dot do not count as alpha-numerical characters a-z A-Z 0-9; either remove it if(ctype_alnum ($_POST['email'])) which proved to be successful in testing this.
You can also use another function such as FILTER_VALIDATE_EMAIL
I quote from the PHP manual:
Return Values
Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
This block has a misplaced brace
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
Which should read as
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
} // was missing
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
// } // was misplaced - commented out to show you
otherwise it would not have written the password (as part of the array) to file.
Plus this $error = ''; should "probably" read as $errors = ''; but that didn't stop it from writing the data to file.
As for the Array message, remove the square brackets [] from all instances of $errors[]
I think
fwrite($fp, print_r($clean, TRUE));
should be
fwrite($fp, $clean, TRUE);
or
file_put_contents($fp, $clean);

Problem with my PHP server-side validation code

I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...

Categories