Why is this piece of code not writing anything into database? - php

I need a second pair of eyes to have a look at my code and tell me what I am missing, as I think I have identified the portion of code that doesn't work, I just don't know why.
Basically I am trying to register a user to a database, in a way that it prevents SQL injection. For the life of me however, it doesn't work. When I deconstruct the code and make it less secure, it works. Anyway, code is here:
//require_once 'sendEmails.php';
session_start();
$username = "";
$email = "";
$user_dob = "";
$user_fname = "";
$user_lname = "";
$user_telephone = "";
$errors = [];
$servername = '';
$login = '';
$password = '';
$DBname = '';
$rows = 0;
$query = "";
$conn = new mysqli($servername, $login, $password, $DBname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn) {
echo "Connected successfully";
}
// SIGN UP USER
if (isset($_POST['signup-btn'])) {
if (empty($_POST['username'])) {
$errors['username'] = 'Username required';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email required';
}
if (empty($_POST['password'])) {
$errors['password'] = 'Password required';
}
if (isset($_POST['password']) && $_POST['password'] !== $_POST['passwordConf']) {
$errors['passwordConf'] = 'The two passwords do not match';
}
if (empty($_POST['dob'])) {
$errors['dob'] = 'Date of birth required';
}
if (empty($_POST['fname'])) {
$errors['fname'] = 'First name required';
}
if (empty($_POST['lname'])) {
$errors['lname'] = 'Last name required';
}
if (empty($_POST['telephone'])) {
$errors['telephone'] = 'Telephone number required';
} //--checks input in browser
//I think it works untill this point...
$token = bin2hex(random_bytes(50)); // generate unique token
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); //encrypt password
$user_dob = $_POST['dob'];
$user_fname = $_POST['fname'];
$user_lname = $_POST['lname'];
$user_telephone = $_POST['telephone'];
$email = $_POST['email'];
//Above assigns inputted values into variables declared at the start
//echo $token, $email; //-- this works
//nl2br() ; // -- line break in php
// Check if email already exists
//$result = $mysqli->query("SELECT * FROM User_tbl WHERE email='$email' LIMIT 1");
$sql = "SELECT * FROM User_tbl WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > $rows) {
$errors[] = $email;
echo "Email already exists";
}
$errorsInt = count($errors);
echo mysqli_num_rows($result);
echo count($errors);
echo $errorsInt;
if ($errorsInt === $rows) {
$query = "INSERT INTO User_tbl SET token=?, username=?, password=?, user_dob=?, user_fname=?, user_lname=?, user_telephone=?, email=?";
// "INSERT INTO User_tbl VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
echo $query;
//---------------------------------------------------------------------------
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
echo $result;
if ($result) {
$user_id = $stmt->insert_id;
$stmt->close();
$_SESSION['id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['verified'] = false;
$_SESSION['message'] = 'You are logged in!';
$_SESSION['type'] = 'alert-success';
header('location: index.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not register user";
}
}
}
The problem I believe starts here:
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();

Related

php user,admin base project with login,signup,abd index page

I'm working on a project which is a user, admin dashboard . first I have a page where is tell user/admin to signup in that i have email, passowrd, cpassword, department, schemes (both are select option field) and designation(like, collector, SdM, ETC) ,and role(user, admin). now then user/admin signup its detail fill in database and then he go to login page and write its email and password and he redirected to login page where also department and schemes select option field .
my question is that what should be logic that when a user/admin signup , the details which he enter and select from select filed that should be displayed to index page .
like he select department(education and its scheme ) so that scheme only display on index page no other department and scheme
i said again my signin and index page is same like 10department and there 50 schemes each of them. user select and he only see on index page that is fill in signin page
just tell me logic
thankyou
code
signin.php
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Connection Established
$server = "localhost";
$username = "root";
$password = "";
$database = "registration";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn){
// echo "success";
// }
// else{
die("Error". mysqli_connect_error());
}
$Email = $_POST["Email"];
$password = $_POST["password"];
$cpassword = $_POST["cpassword"];
$department = $_POST["department"];
$schemes = $_POST["schemes"];
$designation = $_POST["designation"];
$Role = $_POST["Role"];
// $exists=false;
$existSql = "SELECT * FROM `usertable` WHERE Email = '$Email'";
$result = mysqli_query($conn, $existSql);
mysqli_set_charset($conn,'utf8'); // for hindi font language issue
$numExistRows = mysqli_num_rows($result);
if($numExistRows > 0){
// $exists = true;
$showError = "Email Already Exists";
}
else{
// $exists = false;
if(($password == $cpassword)){
$hash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO `usertable` (`Email`,`password`,`department`,`schemes`,`designation`,`Role`, `dt`) VALUES ('$Email', '$hash','$department','$schemes','$designation','$Role', current_timestamp())";
$result = mysqli_query($conn, $sql);
if ($result){
$showAlert = true;
}
}
else{
$showError = "Passwords do not match";
}
}
}
// login.php
<?php
$login = false;
$showError = false;
// db Connection
if($_SERVER["REQUEST_METHOD"] == "POST"){
$server = "localhost";
$username = "root";
$password = "";
$database = "Registration";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn){
// echo "success";
// }
// else{
die("Error". mysqli_connect_error());
}
$Email = $_POST["Email"];
$password = $_POST["password"];
// $sql = "Select * from users where username='$username' AND password='$password'";
$sql = "Select * from usertable where Email='$Email'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);
if ($num == 1){
while($row = mysqli_fetch_assoc($result)){
if (password_verify($password, $row['password'])){
$login = true;
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['Email'] = $Email;
header("location: index.php");
}
else{
$showError = "Invalid Email";
}
}
}
else{
$showError = "Invalid Email Or Password";
}
}
?>

Hashed password not coming out to what it should be (PHP)

So I'm trying to make a fairly simple login system, but for some reason the hashed password that is being sent to my database is not hashing correctly. I checked my database and the stored password is not what the sha256 hashed with the generated salt appended is not what it's supposed to be. Here's my code for generating the hash that's being uploaded to the database:
<?php
include "connection.php";
//Check Connection
if ($connect->connect_error) {
echo "Failed to connect to server: " . mysqli_connect_error();
}
//Reset all Checks
$username_exists = NULL;
$email_valid = NULL;
$passwords_match = NULL;
$password_acceptable = NULL;
$password_long_enough = NULL;
$password = NULL;
//Prepare Statements
//Check for Username Existing Statement
$check_username_match = $connect->stmt_init();
$sql_check_username = "SELECT id FROM $tablename WHERE username=?";
$check_username_match->prepare($sql_check_username);
$check_username_match->bind_param("s", $username);
//Insert Into Table Statement
$register_query = $connect->stmt_init();
$sql_register = "INSERT INTO $tablename (username, email, password, token, active, level) VALUES (?, ?, ?, ?, ?, ?)";
$register_query->prepare($sql_register);
$register_query->bind_param("sssssi", $username, $email, $hashedpassword, $token, $activated, $level);
//Execute When Form Submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$email = mysqli_escape_string($connect, $_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
//Check if Username Exists
$check_username_match->execute();
$check_username_match->store_result();
$numrows = $check_username_match->num_rows;
if ($numrows==0){
$username_exists = false;
} else {
$username_exists=true;
}
//Check if Passwords Match
if ($password==$confirm_password){
$passwords_match = true;
} else {
$passwords_match = false;
}
//Check if Email Address is Valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_valid = true;
} else {
$email_valid = false;
}
//Check if Passwords Contains Special Characters
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
//Check if Password is Long Enough
$password_length = strlen($password);
if ($password_length>8){
$password_long_enough = true;
} else {
$password_long_enough = false;
}
//Validate Password
if(!$uppercase || !$lowercase || !$number || !$password_long_enough || $password = '') {
$password_acceptable = false;
} else {
$password_acceptable = true;
}
//Register if all Validations Met
if(!$username_exists && $email_valid && $passwords_match && $password_acceptable){
//$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$token = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$activated="No";
$level = 0;
$hashedpassword = password_hash($password, PASSWORD_DEFAULT);
$register_query->execute();
$message = "Hello, welcome to the site.\r\n\r\nPlease click on the following link to activate your account:\r\nlocalhost/login_system/activate.php?token=".$token;
mail($email, 'Please Activate Your Account', $message);
header("Location: login.php");
}
}
?>
UPDATE: I changed my above code to reflect the changes I made with password_hash. However, the problem still persists.
This is my login php:
<?php
include("connection.php");
session_start();
//Reset Variables
$message = '';
$location = "/login_system/index.php"; //default location to redirect after logging in
$username = '';
$password = '';
//Check to see if user is newly activated; if he is display a welcome message.
if(isset($_GET['activated'])){
if($_GET['activated'] == "true"){
$message = "Thank you for verifying your account. Please login to continue.";
}
}
//Check to see if user is coming from another page; if he is then store that page location to redirect to after logging in.
if(isset($_GET['location'])) {
$location = htmlspecialchars($_GET['location']);
}
echo $location;
//Prepare login check statement
$check_login = $connect->stmt_init();
$sql = "SELECT id, password FROM $tablename WHERE username=?";
$check_login->prepare($sql);
$check_login->bind_param("s", $username);
//Execute Login Check
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$password = $_POST['password'];
$check_login->execute();
$check_login->store_result();
$numrows = $check_login->num_rows;
$check_login->bind_result($id, $match);
$check_login->fetch();
if ($numrows==1 && password_verify($password, $match)) {
$_SESSION['login_user'] = $id;
$goto = "localhost".$location;
header("location: $goto");
$message = "Success!";
} else {
$message="Username or password is not valid."."<br>".$match."<br>";
}
}
$connect->close();
?>
You should just feed the password you want to hash into PHP's password_hash();function. Like so...
$password = $_POST['password'];
$options = [
'cost' => 12,
];
echo password_hash($password, PASSWORD_BCRYPT, $options);
Then when you want to check if the password exists in the database use password_verify(); Like so...
$password = PASSWORD_HERE;
$stored_hash = HASH_HERE;
if (password_verify($password, $stored_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}

PHP - Convert my deprecated MySQL to MySQLi

I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to the new MySQLi. Please advise me how to modify this script, I would prefer the procedural style.
UPDATE - The MySQLi coding is not working because it would insert into the database like the MySQL coding would, would appreciate if your can help me.
MYSQL
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysql_real_escape_string($_POST['name']);
$name2 = mysql_real_escape_string($_POST['name2']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email2 = mysql_real_escape_string($_POST['email2']);
$address = mysql_real_escape_string($_POST['address']);
$address2 = mysql_real_escape_string($_POST['address2']);
$address3 = mysql_real_escape_string($_POST['address3']);
$address4 = mysql_real_escape_string($_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error");
//select database
mysql_select_db("logindb") or die("Selection Error");
//namecheck
$namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'");
$count = mysql_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysql_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
MYSQLI (NOT WORKING)
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysqli_real_escape_string($connect, $_POST['name']);
$name2 = mysqli_real_escape_string($connect, $_POST['name2']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$password2 = mysqli_real_escape_string($connect, $_POST['password2']);
$email2 = mysqli_real_escape_string($connect, $_POST['email2']);
$address = mysqli_real_escape_string($connect, $_POST['address']);
$address2 = mysqli_real_escape_string($connect, $_POST['address2']);
$address3 = mysqli_real_escape_string($connect, $_POST['address3']);
$address4 = mysqli_real_escape_string($connect, $_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error");
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
$count = mysqli_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
Converting to mysqli is not about adding i to the old library.
The main difference is that mysqli offers prepared statement feature.
This saves you from the tedious task of manually escaping values with mysqli_real_escape_string.
The proper way to do it is to prepare your query:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($connect, $query)) {
mysqli_stmt_bind_param($stmt,'sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/*Count the rows*/
if( mysqli_stmt_num_rows($stmt) > 0){
echo"New Record has id = ".mysqli_stmt_insert_id($stmt);
}else{
printf("Errormessage: %s\n", mysqli_error($connect));
die();
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
In addition to prepared statement, another advantage is the coding style, mysqli introduces OOP style, here is the same code in that style:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = $connect->prepare($query)) {
$stmt->bind_param('sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute query */
$stmt->execute();
/*Count the rows*/
if($stmt->num_rows > 0){
echo"New Record has id = ".$connect->insert_id;
}else{
var_dump($connect->error);
die();
}
/* close statement */
$stmt->close();
}
/* close connection */
$connect->close();
Both would achive the same. Good luck
I noticed one error in your script (mysqli script):
Instead of
$count = mysql_num_rows($namecheck);
do
$count = mysqli_num_rows($namecheck);
You can also check for errors in your query, like this (from w3schools - http://www.w3schools.com/php/func_mysqli_error.asp):
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($con));
}
Also try to do some debugging (echo some results) in your script to find errors.
Pass connection parameter inside
$lastid = mysqli_insert_id();
like
$lastid = mysqli_insert_id($connect);

Password hash returning false

So I have a simple login script, but when I started encrypting passwords and using password_verify I seem to get the same result all the time, false. Here's my login script
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "root";
$dbname = "users";
try{
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8');
$st = $con->prepare("SELECT * FROM users WHERE email = :email AND password = :pass");
$st->bindValue(':email', $email, PDO::PARAM_STR);
$st->bindValue(':pass', $pass, PDO::PARAM_STR);
$st->execute();
$rows = $st->fetch(PDO::FETCH_NUM);
if($email === ''){
$_SESSION['message1'] = 'Enter a valid email';
header('Location: index.php');
exit();
}
elseif($pass === ''){
$_SESSION['message1'] = 'Enter a valid password';
header('Location: index.php');
exit();
}
elseif($rows > 0){
$_SESSION['loggedin'] = true;
$hash = $con->prepare("SELECT password FROM users WHERE email = :email");
$hash->bindValue(':email', $email);
$hash->execute();
}
elseif(password_verify($pass, $hash)){
$name = $con->prepare("SELECT name FROM users WHERE email = :email");
$name->bindValue(':email', $email, PDO::PARAM_STR);
$name->execute();
$rows = $name->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$_SESSION['name'] = $row['name'];
}
header('Location: profile.php');
}
else{
$_SESSION['message1'] = 'Make sure email and password are correct';
header('Location: index.php');
exit();
}
?>
Also here's how I'm encrypting
$passh = password_hash($pass, PASSWORD_DEFAULT)."\n";
$db = $con->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :passh)");
$db->bindValue(':name', $name, PDO::PARAM_STR);
$db->bindValue(':email', $email, PDO::PARAM_STR);
$db->bindValue(':passh', $passh, PDO::PARAM_STR);
$db->execute();
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['loggedin'] = true;
header('Location: profile.php');
exit();
Error reporting is enabled, but for some reason its still not working and simply displays Make sure email and password are correct, which come from the next else statement. Any ideas? I'm fairly new. Also any security tips would be great. Thanks in advance.
UPDATED CODE
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "root";
$dbname = "users";
try{
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $passw);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8');
$hash = $con->prepare("SELECT password FROM users WHERE email = :email");
$hash->bindValue(':email', $email);
$hash->execute();
$rows1 = $hash->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows1 as $row1) {
$_SESSION['hash'] = $row1['hash'];
}
$st = $con->prepare("SELECT * FROM users WHERE email = :email AND password = :pass");
$st->bindValue(':email', $email, PDO::PARAM_STR);
$st->bindValue(':pass', $pass, PDO::PARAM_STR);
$st->execute();
$rows = $st->fetch(PDO::FETCH_NUM);
if($email === ''){
$_SESSION['message1'] = 'Enter a valid email';
header('Location: index.php');
exit();
}
elseif($pass === ''){
$_SESSION['message1'] = 'Enter a valid password';
header('Location: index.php');
exit();
}
elseif($rows > 0 || password_verify($pass, $hash) ){
$_SESSION['loggedin'] = true;
$name = $con->prepare("SELECT name FROM users WHERE email = :email");
$name->bindValue(':email', $email, PDO::PARAM_STR);
$name->execute();
$rows = $name->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$_SESSION['name'] = $row['name'];
}
header('Location: profile.php');
}
else{
$_SESSION['message1'] = 'Make sure email and password are correct';
header('Location: index.php');
exit();
}
?>
Look at your query one more time:
SELECT password FROM users WHERE email = :email
You are selecting the column password,
when you fetch the row you are using the field hash
$_SESSION['hash'] = $row1['hash'];
Unlike you think, your script is not simple at all, you are performing 3 queries on the same record, try this approach
$email = $_POST['email'];
$pass = $_POST['password'];
if($email === ''){
$_SESSION['message1'] = 'Enter a valid email';
header('Location: index.php');
exit();
}
if($pass === ''){
$_SESSION['message1'] = 'Enter a valid password';
header('Location: index.php');
exit();
}
$query = 'SELECT name, email, password
FROM users
WHERE email = :email LIMIT 1';
$stmt = $con->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$row){
$_SESSION['message1'] = 'User does not exist';
header('Location: index.php');
exit();
}
//hashed password from Database
$hash = $row['password'];
if(password_verify($pass, $hash)){
$_SESSION['hash'] = $row['password'];
$_SESSION['name'] = $row['name'];
$_SESSION['email'] = $row['email'];
header('Location: profile.php');
}else{
$_SESSION['message1'] = 'Make sure email and password are correct';
header('Location: index.php');
exit();
}

mysqli prepared statement in login form doesn't work?

I am trying to secure my login form using mysqli prepared statement.
I am using the following code and I'm keep getting the wrong information entered error!
here is my code:
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
// Connect to the MySQL database
include "config/connect.php";
$stmt = mysqli_prepare(
$db_conx,
"SELECT email, password, storeShop
FROM storename
WHERE email = ?
AND password = ?
AND storeShop = ?"
);
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
//after validation, of course
mysqli_stmt_bind_param($stmt, "sss", $manager, $password, $stores);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
mysqli_stmt_close($stmt);//<-- CLEAN UP AFTER YOURSELF!
//update was successful
$id = mysqli_insert_id($db_conx);
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
exit();
} else {
echo "wrong information entered";
exit();
}
}
but when I use this code, it works fine:
$sql = "SELECT * FROM storename WHERE email='$manager' AND password='$password' AND storeShop='$stores'";
$query = mysqli_query($db_conx, $sql);
could someone please tell me what I am doing wrong?
Thanks in advance.
EDIT, This still doesn't work.
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
// Connect to the MySQL database
include "config/connect.php";
$stmt = mysqli_prepare(
$db_conx,
"SELECT email, password, storeShop
FROM members
WHERE email = ?
AND password = ?
AND storeShop = ?"
);
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
//after validation, of course
mysqli_stmt_bind_param($stmt, "sss", $manager, $password, $stores);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
$existCount = mysqli_stmt_affected_rows($stmt);
mysqli_stmt_execute($stmt); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
mysqli_stmt_close($stmt);
exit();
} else {
header("Location: data");
exit();
}
//<-- CLEAN UP AFTER YOURSELF!
//update was successful
}
}
SECOND EDIT:
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
// Connect to the MySQL database
include "config/connect.php";
$stmt = mysqli_prepare(
$db_conx,
"SELECT email, password, storeShop
FROM members
WHERE email = ?
AND password = ?
AND storeShop = ?"
);
$manager = $_POST["email"];
$password = sha1(sha1($_POST['password']).$_POST['password']);
$stores = $_POST["stores"];
//after validation, of course
mysqli_stmt_bind_param($stmt, "sss", $manager, $password, $stores);
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($db_conx))
{
$existCount = mysqli_stmt_affected_rows($stmt); // count the row nums
if ($existCount == 1) { // evaluate the count
if (mysqli_stmt_affected_rows($stmt))
{
while($row = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
mysqli_stmt_close($stmt);
exit();
} else {
header("Location: data");
exit();
}
}
//<-- CLEAN UP AFTER YOURSELF!
//update was successful
}
}
This works for me:
$stmt = $db_conx->prepare("SELECT email, password, storeShop
FROM storename
WHERE email = ?
AND password = ?
AND storeShop = ?");
$stmt->bind_param('sss', $manager, $password, $stores);
$stmt->execute();
$stmt->bind_result($manager, $password, $stores);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
exit();
}
}
else {
header("Location: data");
exit();
}
$stmt->close();
You need to update this;
$existCount = mysqli_num_rows($query);
to
$existCount = mysqli_stmt_affected_rows($stmt);
Refer here for further details
Edit:
And in your code it should be ;
if (mysqli_stmt_affected_rows($stmt))
{
while($row = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
$storeShop = $row["storeShop"];
}
$_SESSION["storeShop"] = $storeShop;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
$_SESSION['storeShop'] = $storeShop;
header("location: dashboard");
mysqli_stmt_close($stmt);
exit();
} else {
header("Location: data");
exit();
}

Categories