How to validate forms - php

I am new in PHP programming and I am creating my first registration and login form. I did everything but there is one problem: How I must sort the code. I tried in lots of ways but it is messed up.
if (filter_input_array(INPUT_POST)) {
if (preg_match('/\s/', $name)) {
$errorName = "Names doesn't contain whitespaces";
$mainError = true;
}
$sql = "SELECT name FROM register WHERE name='$name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (mysqli_num_rows($result) == 1) {
$errorName = 'This name is already registered';
$mainError = true;
}
if (mb_strlen($name) > 0 AND mb_strlen($name) < 3) {
$errorName = 'Name too short';
$mainError = true;
}
if (mb_strlen($name) > 15) {
$errorName = 'Name too long';
$mainError = true;
}
if ($name == '') {
$errorName = 'This field is REQUIRED';
$mainError = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorEmail = "Invalid email";
$mainError = true;
}
if (preg_match('/\s/', $pass1)) {
$errorName = "Password mustn't contain whitespaces";
$mainError = true;
}
if (mb_strlen($pass1) > 0 AND mb_strlen($pass1) < 6) {
$errorPass1 = 'Password too short';
$mainError = true;
}
if (mb_strlen($pass1) > 20) {
$errorPass1 = 'Password too long';
$mainError = true;
}
if ($pass1 == '') {
$errorPass1 = 'This field is REQUIRED';
$mainError = true;
}
if ($pass1 != $pass2) {
$errorPass2 = "Passwords don't match";
$mainError = true;
}
if ($pass2 == '') {
$errorPass2 = 'This field is REQUIRED';
$mainError = true;
}
if (!$mainError) {
$feedback = 'You registered successfully!';
}
}
I want to know what must be first

Related

localhost: data not going into database

i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>

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

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;
}

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 code with oci

For email validation, the condition for checking email exist or not is failed to function and I still able to register using same email. This is code for email validation
if ( !filter_var($bemail,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
**// check email exist or not**
$result = oci_parse($connection,"SELECT BUSER_EMAIL FROM
POHSENG.BRONTE_USER WHERE BUSER_EMAIL= $bemail");
$count = oci_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
This is overall php code. I tried a lot of way to modify but it is not work at all, while in mysqli it is working.
<?php
require 'oci_connect_hugo.php';
$error = false;
$count="";
$bname="";
$bemail="";
$baddress="";
$bpass="";
$nameError = "";
$emailError ="";
$addError ="";
$passError = "";
if ( isset($_POST['signup']) ) {
// clean user inputs to prevent sql injections
$bname = trim($_POST['bname']);
$bname = strip_tags($bname);
$bname = htmlspecialchars($bname);
$bemail = trim($_POST['bemail']);
$bemail = strip_tags($bemail);
$bemail = htmlspecialchars($bemail);
$baddress =trim($_POST['baddress']);
$baddress = strip_tags($baddress);
$baddress = htmlspecialchars($baddress);
$bpass = trim($_POST['bpass']);
$bpass = strip_tags($bpass);
$bpass = htmlspecialchars($bpass);
// basic name validation
if (empty($bname)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($bname) < 3) {
$error = true;
$nameError = "Name must have at least 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$bname)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//basic email validation
if ( !filter_var($bemail,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
**// check email exist or not**
$result = oci_parse($connection,"SELECT BUSER_EMAIL FROM
POHSENG.BRONTE_USER WHERE BUSER_EMAIL= $bemail");
$count = oci_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
if (empty($baddress)) {
$error = true;
$addError = "Please enter your address.";
}
// password validation
if (empty($bpass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($bpass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
}
// password encrypt using SHA256();
$bpass = hash('sha256', $bpass);
// if there's no error, continue to signup
if( !$error ) {
$res = oci_parse($connection,"insert into
POHSENG.BRONTE_USER(BUSER_NAME, BUSER_EMAIL, BUSER_ADDRESS,
BUSER_PASSWORD) VALUES('$bname','$bemail','$baddress','$bpass')");
oci_execute($res);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($bname);
unset($bemail);
unset($bpass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>

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);

Categories