php validation and mongodb - php

I'm making a registration form using PHP and mongodb. This form works but the problem is it's not carrying out the validations. Even if I leave all the fields empty, it updates the database with the empty fields. Its as if the whole error = array(); is invisible.
What I need is for it to perform the checks and not update the database until all the requirements are met.
<?php
session_start();
if($_POST['submit']){
$ScName=strip_tags($_POST['ScName']);
$fname=strip_tags($_POST['fname']);
$lname=strip_tags($_POST['lname']);
$email=strip_tags($_POST['email']);
$password=strip_tags($_POST['password']);
$password2=strip_tags($_POST['password2']);
$error = array();
if(empty($email) or !filter_var($email,FILTER_SANITIZE_EMAIL)){
$error[] = "Email id is empty or invalid";
}
if(empty($password)){
$error[] = "Please enter password";
}
if(empty($password2)){
$error[] = "Please Confirm password";
}
if($password != $password2){
$error[] = "Password and Confirm password are not matching";
}
if(empty($fname)){
$error[] = "Enter first name";
}
if(empty($lname)){
$error[] = "Enter last name";
}
if(count($error == 0)){
//database configuration
$host = 'localhost';
$database_name = 'mongo1';
$database_user_name = '';
$database_password = '';
$connection=new Mongo('localhost');
if($connection){
//connecting to database
$database=$connection->user;
//connect to specific collection
$collection=$database->user;
$query=array('email'=>$email);
//check for existing username
//$query=array('ScName'=>$ScName);
//checking for existing user
$count=$collection->findOne($query);
if(!count($count)){
//Save the New user
$user=array('fname'=>$fname,'lname'=>$lname,'ScName'=>$ScName,'email'=>$email,'password'=>md5($password));
$collection->save($user);
echo "You are successfully registered.";
}else{
echo "Email already exists.Please register with another Email";
}
}else{
die("Database is not connected");
}
}else{
//Displaying the error
foreach($error as $err){
echo $err.'</br>';
}
}
}
?>

You have misplaced the bracket at
if(count($error == 0)){
Since $error == 0 is false, as $error is a populated array, count(false) evaluates as 0 (i.e., false), and the if branch doesn't execute. You should close the bracket after $error:
if (count($error) == 0) {

Related

php redirect to another page after validation

I am trying to figure out how to redirect after validation of a form (i.e after conditions for my form have been met)(I have the header at the end of the PHP code). I have a basic form ,and I know this should be a straightforward code of line but I can't seem to make it work! Your advice is very much appreciated!
<?php
$firstNameErr = '';
$lastNameErr = '';
$emailErr='';
$passwordErr = '';
$passwordConfErr='';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$firstName = $_POST["firstName"];
if(empty($firstName)){
$firstNameErr = "First Name is required";
}
else if(!preg_match("/^[a-zA-Z]+$/", $firstName)){
$firstNameErr= "Only letters, no spaces or special characters allowed";
}
else{
$firstNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$lastName = $_POST["lastName"];
if(empty($lastName)){
$lastNameErr = "Last Name is required";
}
else if(!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $lastName)){
$lastNameErr = "No Special characters or numbers allowed";
}
else{
$lastNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST["email"];
if(empty($email)){
$emailErr = "Email is required";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
else{
$emailErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$password=$_POST["password"];
if(empty($password)){
$passwordErr = "Please Enter your password";
}
else if (strlen($password) < "8") {
$passwordErr = "Your Password Must Contain At Least 8 Digits !";
}
else if(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number !";
}
else if(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter !";
}
else if(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter !";
}
else if(!preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $password)) {
$passwordErr = "Your Password Must Contain At Least 1 Special Character !";
}
else{
$passwordErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$confirmPassword = $_POST["confirmPassword"];
$password = $_POST["password"];
if(empty($confirmPassword)){
$passwordConfErr = "Please Enter your password";
}
else if($password!=$confirmPassword){
$passwordConfErr = "Passwords do not match";
}
else{
$passwordConfErr="Valid";
}
}
else{
echo "Form not submitted with POST";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['Register']) and $firstNameErr == "Valid" and $lastNameErr =="Valid" and $emailErr == "Valid" and $passwordErr == "Valid" and $passwordConfErr=="Valid") {
header("Location: profile.php");
exit();
}
}
A single if ($_SERVER["REQUEST_METHOD"] == "POST"){ which wraps all $_POST logic would suffice, then depending on your app (if its mostly AJAX) you should use a response/request flow so the POST logic is at the top and it falls through to the view with the errors which can then be used in the view, or you should return JSON and do an AJAX request, else you won't be able to pick up the errors unless you put them into the session and then pick them up on redirect which is just extra steps.
Example request/response, for a single page i.e register.php, this could be broken out where you load the HTML via an include or view loader but the idea is the same.
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
header("Location: profile.php");
exit();
}
// otherwise continue to form
} ?>
<form>
...
<input name="firstName" value="<?= htmlspecialchars($_POST['firstName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['firstName']) ? '<span class="form-error">'.$errors['firstName'].'</span>' : '' ?>
<input name="lastName" value="<?= htmlspecialchars($_POST['lastName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['lastName']) ? '<span class="form-error">'.$errors['lastName'].'</span>' : '' ?>
</form>
Or if your going to use mostly AJAX, another way would be to return JSON, then you can access the errors to then build out the dom from the AJAX response.
<?php
//
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// set json response header
header('Content-type: application/json;charset=utf-8');
// Is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//
$errors = [];
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
echo json_encode(['status' => 200]);
exit();
}
echo json_encode(['errors' => $errors]);
exit();
} else {
header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
echo json_encode(['status' => 405]);
}
} else {
header('Location: /');
}
In both examples, use a single errors array then its easy to access and all in one place. You also don't need to set additional vars from the $_POST['...'] vars to validate them.
Your validating code should look like this:
$Name = $Surname = $username = $password = $confirm_password =
$email ="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Name.
if (empty(trim($_POST["firstName"]))) {
$errors[] = 'name required.';
} else {
$Name = $_POST["firstName"];
}
// Validate lastName.
if (empty(trim($_POST["lastName"]))) {
$errors[] = 'surname required.';
} else {
$Surname = $_POST["lastName"];
}
// Validate username
if (!preg_match("/^[a-zA-Z]+$/", $_POST["username"])) {
$errors['username'] = "Only letters, no spaces or special characters allowed";
}
// Validate username from database to see if username already exist.
//You can check for the email is well.
if(empty(trim($_POST["username"]))){
$errors[] = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = :username";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() == 1){
$errors[] = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->closeCursor();
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$errors[] = "Enter password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$errors[] = "password should be min 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$errors[] = "confirm pass.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if($password != $confirm_password){
$errors[] = "pass no matches.";
}
}
// Validate Email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email = $_POST["email"];
} else {
$errors[] = "invalid email type.";
}
// Validate Email
if(empty(trim($_POST["email"]))){
$errors[] = 'email required.';
}else {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
}
if(empty($errors)){
//if no errors
//Do everythin else in here
//Do insert query after you are done redirect to profile page
header("Location: profile.php");
exit();
}
}
To get eroors :
<?php if(isset($errors)) {?>
<div class="error">
<?php echo implode('<br/>', $errors); ?>
</div>
<?php } unset($_SESSION['errors']); ?>
And your html form here if its in same page :
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
//inputs etc..
</form>

PHP doesn't work properly when hosted

I have made a Log in and Sign up system and on my localhost it worked properly but when i hosted it and created account it says Incorrect credentials. I will send a code if it is needed. And i have crated a MySql db.
Site link: http://metallicafanpage.esy.es
I am using Hostinger
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
Here is Register.php
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT userEmail FROM users WHERE userEmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
This Is Because Of Your Php Mysql version Your Hosting Server Is Just Using An Old Php Or Mysql Version

After hashing the password using md5() and store it into database,cant login again

i built a login and registration system before,is running well.After I hash the input password using md5()and store it to the database,it cant login anymore.So everyone pls look at my code here,so i can know what goes wrong..here is my code here..
signup.php
include ('config.php');
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=htmlentities($_POST['username']);
$password=htmlentities($_POST['password']);
$email=htmlentities($_POST['email']);
$cpassword=htmlentities($_POST['cpassword']);
//not empty
//at least 3 characters long
//username and password cannot be same
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
else if (strlen($username)<6 ) {
$errors['username2'] = "Username should at least 6 characters long";
}
else if (!preg_match('/^[a-z\d_]{3,20}$/i', $username)) {
$errors['username3'] = "Username should contain letters and numbers only.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
else if (strlen($password) <8) {
$errors['password2'] ="Password should at least 8 characters long";
}
else if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,20}$/', $password)){
$errors['password3'] ="Password should contain at least 1 upper-case,1 lower-case,numbers ";
}
//check the password confirmation
if(empty($cpassword)) {
$errors["cpassword2"] = "Must confirm your password to proceed";
}
if($password != $cpassword){
$errors['cpassword1']="Password do not match";
}
//check whether username or password is same
if($username == $password){
$errors['sameuserpass'] ="Username and password cannot be same";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email3'] ="Please enter a vaild email address";
}
//check the errors
if(count($errors) == 0){
$query=mysqli_query($con,"SELECT * FROM user WHERE Username='$username'");
$query1=mysqli_query($con,"SELECT*FROM user WHERE Email='$email'");
if(mysqli_num_rows($query) > 0) {
$errors['userexist'] ="Username already exists";
}
else if(mysqli_num_rows($query1) > 0){
$errors['emailexist'] = "Email already already exists";
}
else {
//HASHING THE PASSWORD
$password = md5($password);
$queryinsert= "INSERT INTO user(Username,Password,Email) VALUES ('$username','$password','$email')";
mysqli_query($con,$queryinsert);
header("Location:login.php");
}
}
}
login.php
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = htmlentities($_POST['email']);
$password = htmlentities(md5($_POST['password']));
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' ");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
if($dbemail === $email&&$dbpassword === $password)
{
$_SESSION['email']="$email";
header('Location:user.html');
exit;
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>
I successfully store the password that hashed into the database,but the problem is cant login again although the email address and password is correct.Any idea?
signup.php
include ('config.php');
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$cpassword=mysqli_real_escape_string($con,$_POST['cpassword']);
//not empty
//at least 3 characters long
//username and password cannot be same
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
else if (strlen($username)<6 ) {
$errors['username2'] = "Username should at least 6 characters long";
}
else if (!preg_match('/^[a-z\d_]{3,20}$/i', $username)) {
$errors['username3'] = "Username should contain letters and numbers only.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
else if (strlen($password) <8) {
$errors['password2'] ="Password should at least 8 characters long";
}
else if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,20}$/', $password)){
$errors['password3'] ="Password should contain at least 1 upper-case,1 lower-case,numbers ";
}
//check the password confirmation
if(empty($cpassword)) {
$errors["cpassword2"] = "Must confirm your password to proceed";
}
if($password != $cpassword){
$errors['cpassword1']="Password do not match";
}
//check whether username or password is same
if($username == $password){
$errors['sameuserpass'] ="Username and password cannot be same";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email3'] ="Please enter a vaild email address";
}
//check the errors
if(count($errors) == 0){
$query=mysqli_query($con,"SELECT * FROM user WHERE Username='$username'");
$query1=mysqli_query($con,"SELECT*FROM user WHERE Email='$email'");
if(mysqli_num_rows($query) > 0) {
$errors['userexist'] ="Username already exists";
}
else if(mysqli_num_rows($query1) > 0){
$errors['emailexist'] = "Email already already exists";
}
else {
//HASHING THE PASSWORD
$password = md5($password);
$queryinsert= "INSERT INTO user(Username,Password,Email) VALUES ('$username','$password','$email')";
mysqli_query($con,$queryinsert);
header("Location:login.php");
}
}
}
login.php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$password = md5($password);
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' ");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows != 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
if($dbemail == $email && $dbpassword == $password)
{
$_SESSION['email']="$email";
header('Location:user.html');
exit;
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
This line?
if($dbemail === $email&&$dbpassword === $password)
Shouldn't it be:
if($dbemail == $email&&$dbpassword == $password)
Edit:
And did you change your original password to a md5 hash or re-register
If you need a hash for your Db password - This -> 2aefc34200a294a3cc7db81b43a81873 will change your password to admins
Edit 2:
And I do recommend that you don't use md5 but this instead.
http://php.net/manual/en/function.password-hash.php

Having difficulties with my PHP registration script

This script seems to get hung up when it hits the series of "if" statements checking the email and password length. If I remove these statements, it properly inserts the data into the db.
<?php
ob_start();
session_start();
if (!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['confirmpassword'])) {
$email = strip_tags($_POST['email']);
$password = md5(strip_tags($_POST['password']));
$confirmpassword = md5(strip_tags($_POST['confirmpassword']));
$errors = array();
if (strlen($email) < 6) {
$errors[] = "Email too short.";
}
if (strlen($email) > 25) {
$errors[] = "Email too long.";
}
if (strlen($password) < 2) {
$errors[] = "Password too short.";
}
if (strlen($password) > 25) {
$errors[] = "Password too short.";
}
if ($password !== $confirmpassword) {
$errors[] = "Passwords do not match.";
}
if (count($errors) == 0) {
// Include database config file then connect to database
require('db_config.php');
$connection = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD) or die("Database Connection Error");
$database = mysql_select_db(DB_NAME) or die("No Database");
// Create query
$query = "INSERT INTO bah_register VALUES ('','$email','$password')";
// Query database and
mysql_query($query);
// Success message
echo "Thanks for signing up!";
} else {
foreach ($errors as $error) {
echo $error . "<br />";
}
}
}
?>
Your issue is that you are md5ing the password before you check the length. This puts the password at 32 characters, which is greater than your limit and producing an error.
You are checking strlen($password) > 25 and your password is md5 hashsum which is longer than 25 symbols. You probably wanted to check original value of password
i don't know what is wrong with your code, but for your email you might consider using something like this :
if(!preg_match('/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)){
$errors[] = "Email is not valid.";
}
many emails are longer than 25 characters.
The foreach with the error array can easly be replaced with following code
echo implode('<br />', $errors);
Proper email validation can be done with the filter_var function
The strip_tags function can have undesired effects on the password, probably parts of it will be deleted. Think of the following password: «<my>super!password»

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