User Add/login form Issue - php

I made a simple User Add/login form .But i cannot extract or add data to database using array and need simple procedure.
<?php
//User_Add_Page
if(isset($_POST['userid'],$_POST['username'],$_POST['password'],$_POST['sex'],$_POST['desig']))
{
include("connect.php");
$badchars='!#£$%^&*()+=-][\;/.,`~<>?:"|{} \'';
$userid=$_POST['userid'];
$username=$_POST['username'];
$password=$_POST['password'];
$sex=$_POST['sex'];
$desig=$_POST['desig'];
$errors=array();
if(empty($userid)&& empty($username) && empty($password) && empty($sex) && empty($design))
{
$errors[]= "All Fields Require";
}
else if($userid=="")
{
$errors[]= "Enter User ID";
}
else if (strpbrk($userid, $badchars) !== false)
{
$errors[]= 'INVALID User ID...';
}
else if(strlen($userid)<5 && $username != "")
{
$errors[]='User ID Must be Greater than 5 Characters';
}
else if(is_numeric ($userid))
{
$errors[]= 'User ID Must Conatin Both letters AND character';
}
else if(strlen($userid)>20 && $username != "")
{
$errors[]= 'User ID Must be Less Than 20 Characters';
}
else if($username=="")
{
$errors[]= "Enter username";
}
else if(strlen($username)>30)
{
$errors[]= "Enter username less than 30 char.";
}
else if(!ctype_alpha(str_replace(' ','',$username)))//search alphabetic char. from username
{
$errors[]='Name Must be Character Only';
}
else if($password == "")
{
$errors[]= 'Please Enter Password';
}
else if(strlen($password)<5 && $password != "")
{
$errors[]= 'Password Must Be Greater Than 5 Characters';
}
else if($desig == "")
{
$errors[]= 'Please Enter Designation';
}
else if(empty($errors))
{
$write=("INSERT INTO adduser VALUES ('','$userid','$username','$password','$sex','$desig')");
$time = 1; //Time (in seconds) to wait.
$url = "add_user_process.php"; //Location to send to.
header("Refresh: $time; url=$url");
}
}
?>

else if(empty($errors))
{
$write=("INSERT INTO adduser VALUES ('','$userid','$username','$password','$sex','$desig')");
mysqli_query($write,Your_connection_string)
$time = 1; //Time (in seconds) to wait.
$url = "add_user_process.php"; //Location to send to.
header("Refresh: $time; url=$url");
}

After your "INSERT INTO" you have to specify mysql_query object ,
like $result = mysql_query($write);
Like this ,
$write="INSERT INTO adduser VALUES ('','$userid','$username','$password','$sex','$desig')";
$result = mysql_query($write);

Related

email validation one condition & more than one else statement in PHP

I will try to put email validation with have more than one case.
First(if):email is required.
Second(if): invalid format of email.
Third(else): Email is exist(Active User)
Fourth(else): Email is in approve(Admin is not approved account yet so its
still in request table)
Fifth(else):Everything goes well,post the data into database.
I try to solve this by if-else statement but in last two case I do not have any condition its just have to pass that validation.I also try switch statement, but it's not go after the first case:
Here is my validation:
if(empty($_POST['email']))
{
$email=$_POST['email'];
$emailError="Email is required";
$error=true;
}
else
{
$email=$_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "Invalid email format";
$error=true;
}
else
{
$sql="SELECT * FROM user WHERE email='$email'";
$res=mysqli_query($db,$sql);
if (mysqli_num_rows($res) > 0)
{
$emailError = "Email already exists";
$error=true;
}
}
else
{
$sl="SELECT * FROM request WHERE email='$email'";
$ress=mysqli_query($db,$sl);
if (mysqli_num_rows($ress) > 0)
{
$emailError = "Your Accout is in process";
$error=true;
}
}
}
Following is the way to do this:
Declare some random variables for each error
By using the multiple if conditions make a first check if it is empty or not. Made a second check if it's match the correct format, third if value exist in db or not
I'm displaying the sample code for this
if(empty($_POST['email'])){
$emptyMail = 'Please provide the Email';
}else{
$notEmpty= 1;
}
if(!){ //check the preg match
wrongFromat = 'Please enter the Mail in correct format';
}else{
$correctFormat = 1;
}
if($notEmpty= 1 && $correctFormat = 1){ //check the database
//if it exist in db
$exist = 0;
}elseif($notEmpty= 0 || $correctFormat = 0 || $notEmpty= 1 || $correctFormat = 1){
$exist = 0;
}else{
$exist = 1;
}
if($notEmpty= 1 && $correctFormat = 1 $exist = 1){
//insert in database and send the status pending to the user
}
In line 1 you check if(empty($_POST['email'])),
so if it is empty you should return error, instead you try to save empty value in line 3 and so on.
ok I put the condition for $error & now its working fine. remember that you have to put $exist=""; in starting.
here is my code:
if(empty($_POST['email']))
{
$email=$_POST['email'];
$emailError="Email is required";
$error=true;
}
else {
$email=$_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "Invalid email format";
$error=true;
}
else
{
$sql="SELECT * FROM user WHERE email='$email'";
$res=mysqli_query($db,$sql);
if (mysqli_num_rows($res) > 0)
{
$emailError = "Email already exists";
$error=true;
$exist=1;
}
}
if($exist!=1)
{
$sl="SELECT * FROM request WHERE email='$email'";
$ress=mysqli_query($db,$sl);
if (mysqli_num_rows($ress) > 0)
{
$emailError = "Your Accout is in process";
$error=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

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