I am making a login form for my website. When I click submit on my login form it doesn't seem to run the SELECT statement as it is in my code.
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '$emailclean' AND password = '$passwordclean'");
if($row = mysqli_fetch_assoc($result)){
$finalmessager['success'] = 'You are logged in';
$_SESSION['finalmessager']= $finalmessager;
}else{
$finalmessager['fail'] = 'You are not logged in';
$_SESSION['finalmessager']= $finalmessager;
}
It seems to identify $emailclean but it doesn't seem to read $passwordclean. However, when I try to manually put the password such as
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '$emailclean' AND password = 'celenelqdekdnnd.......'");
it seems to work fine.
What am I doing wrong here?
This is my Code:
require "../config/init.php";
require "../config/config.php";
if(isset($_POST['submit'])){
$passwordclean = mysqli_real_escape_string($mysqli_conn, hash("sha512", $_POST['password']));
$emailclean= mysqli_real_escape_string($mysqli_conn, $_POST['email']);
$errorCheckr = array(); //an array is introduced to check errors
$finalmessager = array();//an array to display final message
if (empty($emailclean)) {
$errorCheckr['emailcheck'] = 'Please enter your email';
}else{
$_SESSION['email'] = $emailclean;
}
if (empty($passwordclean)) {
$errorCheckr['passwordcheck'] = 'Please enter your password';
}else{
$_SESSION['password'] = $passwordclean;
}
//Sanitize
if (!empty($emailclean) && !filter_var($emailclean, FILTER_VALIDATE_EMAIL)) {
$errorCheckr['emailvalidcheck'] = 'Your email is not valid';
}
if (strlen($email) > 50) {
$errorCheckr['emaillengthcheck'] = 'Your email is too long';
}
if (!empty($passwordclean) && strlen($passwordclean) < 5) {
$errorCheckr['passwordlengthcheck'] = 'Your password is too short';
}
if (empty($errorCheckr)) {
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '$emailclean' AND password = '$passwordclean'");
if($row = mysqli_fetch_assoc($result)){
$finalmessager['success'] = 'You are logged in';
$_SESSION['finalmessager']= $finalmessager;
}else{
$finalmessager['fail'] = 'You are not logged in';
$_SESSION['finalmessager']= $finalmessager;
}
unset($_SESSION['email']);
unset($_SESSION['password']);
header('location:../loginform.php');
}else{
$_SESSION['regErrors']= $errorCheckr;
header('location:../loginform.php');
}
}
First turn on errors:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
Test if post variable and password is set:
<?php
var_dump($_POST['password']);
var_dump($passwordclean);
Few tips:
1) Why save the password in a session?
2) You're checking the length of $passwordclean which will always be 128 chars since it is being hashed with sha512.
3) :
<?php
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '". mysqli_real_escape_string($mysqli_conn, $_POST['email']) ."' AND password = '". mysqli_real_escape_string($mysqli_conn, hash("sha512", $_POST['password'])) ."'");
Related
After several cross checks, I created another account to be sure of the error, I am using password_hash with PASSWORD_DEFAULT algorithm. I am not sure where in my code I am not getting, but if I enter a wrong Email I get a different error message for the Email. Your assistance will be greatly appreciated.
<?php
$email_err = $password_err = $login_err = "";
//if user click login button
if(isset($_POST['login'])){
$Email = mysqli_real_escape_string($tie_in, $_POST['email']);
$Password = mysqli_real_escape_string($tie_in, $_POST['Password']);
$check_email = "SELECT * FROM accounts WHERE email = '$Email'";
$res = mysqli_query($tie_in, $check_email);
if(mysqli_num_rows($res) > 0){
$fetch = mysqli_fetch_assoc($res);
$fetch_pass = $fetch['password'];
if(password_verify($Password, $fetch_pass)){
$_SESSION['email'] = $Email;
$status = $fetch['status'];
if($status == 'verified'){
$_SESSION['email'] = $Email;
$_SESSION['Password'] = $Password;
header('location: index.html');
}else{
$info = "This account haven't been verified yet! - $email";
$_SESSION['info'] = $info;
header('location: verifying.php');
}
}else{
$login_err = "Incorrect Password!";
}
}else{
$login_err = "This account is not yet registered, Click on the bottom link to signup.";
}
}
?>
i made simple form for register and connect it to database.
If i sign up for the first time, it allowed me to login and go to main page.
however after i log out and trying to login again it always shows "Incorrect password or email" even i put everything correctly.
tried to reset password, password successfully reset but when i try to login it just showing me same error again.
heres the register php code that im using
//if user signup button
if(isset($_POST['signup'])){
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
if($password !== $cpassword){
$errors['password'] = "Confirm password not matched!";
}
$email_check = "SELECT * FROM usertable WHERE email = '$email'";
$res = mysqli_query($con, $email_check);
if(mysqli_num_rows($res) > 0){
$errors['email'] = "Email that you have entered is already exist!";
}
if(count($errors) === 0){
$encpass = $password;
$code = rand(999999, 111111);
$status = "notverified";
$insert_data = "INSERT INTO usertable (name, email, password, code, status)
values('$name', '$email', '$encpass', '$code', '$status')";
$data_check = mysqli_query($con, $insert_data);
if($data_check){
$subject = "Email Verification Code";
$message = "Your verification code is $code";
$sender = "From: blahblah#example.com";
if(mail($email, $subject, $message, $sender)){
$info = "We've sent a verification code to your email - $email";
$_SESSION['info'] = $info;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header('location: user-otp.php');
exit();
}else{
$errors['otp-error'] = "Failed while sending code!";
}
}else{
$errors['db-error'] = "Failed while inserting data into database!";
}
}
}
And this is login php script im using
//if user click login button
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$check_email = "SELECT * FROM usertable WHERE email = '$email'";
$res = mysqli_query($con, $check_email);
if(mysqli_num_rows($res) > 0){
$fetch = mysqli_fetch_assoc($res);
$fetch_pass = $fetch['password'];
if(password_verify($password, $fetch_pass)){
$_SESSION['email'] = $email;
$status = $fetch['status'];
if($status == 'verified'){
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header('location: index.php');
}else{
$info = "It's look like you haven't still verify your email - $email";
$_SESSION['info'] = $info;
header('location: user-otp.php');
}
}else{
$errors['email'] = "Incorrect email or password!";
}
}else{
$errors['email'] = "It's look like you're not yet a member! Click on the bottom link to signup.";
}
}
When you register new user from your register page, you store plain password into your usertable. Suppose, when you put password = 123, it will store 123 into your password column in your usertable.
But when you try to login with same password 123, your login page logic say the password should be verify with password_verify method.
This method check the password with Hashing algorithm. That's why you are seeing incorect message. You may change the login page logic
From if(password_verify($password, $fetch_pass)) to if($password == $fetch_pass)
Or use properly password_verify method.
I imneed to display logged in/authenticated user's id in html page. My sign in script is below followed by the display script. I've been on it for quite a while. I need to display logged in user's id from the mysql database to html.
<?php
session_start();
include_once('server.php');
$error = false;
if(isset($_POST['btn-login'])){
$username = trim($_POST['username']);
$username = htmlspecialchars(strip_tags($username));
$password = trim($_POST['password']);
$password = htmlspecialchars(strip_tags($password));
if(empty($username)){
$error = true;
$errorUsername = 'Please Input Username';
}
if(empty($password)){
$error = true;
$errorPassword = 'Please Input Password';
}elseif(strlen($password)< 6){
$error = true;
$errorPassword = 'Password must be at least six characters';
}
if(!$error)
{
$password = md5($password);
$sql = "select * from users where username = '$username'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($count==1 && $row['password'] == $password){
$_SESSION['username'] = $row['username'];
header('location: loggedin.php');
}else{
$errorMsg = 'Invalid Username or Password';
}
?>
//display script
<?php
session_start();
echo 'welcome user'.$_SESSION['id'];
?>
You need to set session like this.
$_SESSION['id'] = row['id'];
You are not getting the id value because $_SESSION['id'] is null.
to display the loged user
change this:
echo 'welcome user'.$_SESSION['id'];
to this:
echo 'welcome user'.$_SESSION['username'];
because $_SESSION['id'] is not set and you most probably dont want to show it in the html page so just use the user name or set it to somthing more natural like actual name if it exists in your db row.
I have created registration form which sends a link via e-mail and you have to click it in order to be successfully registered, which makes you have to log in. The problem is that I can't log in, while everything else is working fine. Below you will find my register.php, activation.php and login.php. Any help would be great.
action = register.php
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}else{
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST['email'])) {
$email = $_POST['email'];
}else{
$error[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
action = activation
if ($_GET['action'] == 'invitation') {
if (!empty($_GET['key'])){
//thelw na eleksw an afto to key uparxei sto tabale members
$sql = "SELECT * FROM members WHERE activationCode = '".$_GET['key']."'";
$result=mysql_query($sql,$lnk);
$user= mysql_fetch_assoc($result);
if(!empty($user)){
//edw tha energopoiisw ton xristi
$sql = "UPDATE members SET flag=1 WHERE username = '".$user['username']."'";
mysql_query($sql,$lnk);
}else{
echo "this is WRONG";
}
}else{
echo 'No key';
}
}
action = login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
you are doing wrong with password.
use below code
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}else{
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST['email'])) {
$email = $_POST['email'];
}else{
$error[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = md5($_POST['password']);
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
and for login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = md5($_POST['password']);
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
I'm guessing the error is here:
action = login
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true)); // HERE
}
You've just changed your password into something completely random, then you are trying to look for it in the database...
The key to programming is understanding what you are doing and knowing methods to determine what is wrong. It is ALL about problem solving. As you can see in your code: (action = login)
else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
You generate a random password each time rather than hashing the password that was provided. You then go on to check if it exists with the user. You need to make it like your registration method:
$password = md5($_POST['password']);
Another problem you have is in your query to check for valid user. Your flag field is an int but you're treating it like a string.
AND flag = '1' ";
needs to be
AND flag = 1 ";
NOTICE: DO NOT USE MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO. You are also wide open for SQL injections, be careful.
I am trying to input a check-box for terms and conditions in a form, but when I registered the form without ticking the box the registration went through , (which was not suppose to be). Please help have a look.
<?php
echo "<h2>Register</h2>";
$submit = $_POST['register'];
//form data
$fullname = mysql_real_escape_string(htmlentities(strip_tags($_POST['fullname'])));
$username = strtolower(mysql_real_escape_string(htmlentities(strip_tags($_POST['username']))));
$password = mysql_real_escape_string(htmlentities(strip_tags($_POST['password'])));
$repeatpassword = mysql_real_escape_string(htmlentities(strip_tags($_POST['repeatpassword'])));
$email = mysql_real_escape_string(htmlentities(strip_tags($_POST['email'])));
$houseno = mysql_real_escape_string(htmlentities(strip_tags($_POST['houseno'])));
$addressa = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressa'])));
$addressb = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressb'])));
$addressc = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressc'])));
$county = mysql_real_escape_string(htmlentities(strip_tags($_POST['county'])));
$state = mysql_real_escape_string(htmlentities(strip_tags($_POST['state'])));
$country = mysql_real_escape_string(htmlentities(strip_tags($_POST['country'])));
$accept = mysql_real_escape_string(htmlentities(strip_tags($_POST['accept'])));
if ($submit)
{
$namecheck = mysql_query("SELECT username FROM reusers WHERE username='$username'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("Username already taken!");
}
//check for registration form details
if ($fullname&&$username&&$password&&$repeatpassword&&$email&&$houseno&&$addressa&&$county&&$state&&$country)
{
if($accept!= 1)
{
if ($password==$repeatpassword)
{
//check char lenght of username and fullname
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Lenght of username or fullname is too long";
}
else
{
//check password length
if(strlen($password)>25||strlen($password)<6)
{
echo"Password must be between 6 and 25 characters";
}
else
{
//check password length
$emailcheck = mysql_query("SELECT email FROM reusers WHERE email='$email'");
$ecount = mysql_num_rows($emailcheck);
if($ecount!=0)
{
echo"email already registered Please sign in into your account to continue";
}
else
{
//generate random code
$code = rand(11111111,99999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: donotreply#reacheasy.co.uk";
$body = " Hello $fullname,\n\nUsername $username,\n\n Password $password ,\n\nYou registered `and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://reach.co.uk/activate.php?code=$code\n\nThanks!";
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
//register the user!
//encript password
$password = md5($password);
$repeatpassword = md5($repeatpassword);
$queryreg = mysql_query("
INSERT INTO reusers VALUES ('','$fullname','$username','$password','$email','$code','0','houseno','addressa','addressb','addressc','county','state','country')
");
die("You have been registered successfully! Please check your email ($email) to activate your account<a href='index.php'>Return to login page</a>");
}
}
}
}
}
else
echo"Your passwords do not match!";
}
else
echo"Please read and accept Terms and Conditions before registering!";
}
else
echo "Please fill in <b>all</> fields!";
}
?>
$accept = ($_POST['accept'] ? 1:0);
You must use
if($accept == 1)
because $_POST['accept'] = 1 when you check the checkbox.
Now return Please read and accept Terms and Conditions before registering! when checkbox is checked and register the user when checkbox is not checked.