password_verify() expects parameter 2 to be string - php

Getting this error during attempt to login to member account:
Fatal error: Uncaught TypeError: password_verify() expects parameter 2 to be string, null given in C:\xampp\htdocs\e_id\login.php:77
Stack trace:
#0 C:\xampp\htdocs\e_id\login.php(77): password_verify('password', NULL)
#1 {main} thrown in C:\xampp\htdocs\e_id\login.php on line 77
<?php
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include 'config.php';
// check if user is already logged in
if (is_logged() === true)
{
//Redirect user to homepage page after 5 seconds.
header("refresh:2;url=home.php");
exit;
}
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST["login_username_or_email"]) &&
isset($_POST["login_password"]))
{
$username_or_email = trim($_POST["login_username_or_email"]);
$password = $_POST["login_password"];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
//Select Username or Email to check against Mysql DB if they are
already registered or not.
$stmt = mysqli_stmt_init($conn);
$stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM
users WHERE usernames = ? OR emails = ?");
mysqli_stmt_bind_param($stmt, 'ss', $username,
$email_confirmation);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
*/
if(strpos("$username_or_email", "#") === true)
{
$email = $username_or_email;
$username = "";
$stmt = mysqli_prepare($conn, "SELECT emails FROM users
WHERE emails = ?");
mysqli_stmt_bind_param($stmt, 's', $email);
}
else
{
$username = $username_or_email;
$email = "";
$stmt = mysqli_prepare($conn, "SELECT usernames FROM
users WHERE usernames = ?");
mysqli_stmt_bind_param($stmt, 's', $username);
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf("%s (%s)\n",$row["usernames"],$row["passwords"]);
var_dump($row);
// Check if inputted Username or Email is registered or not.
if (!$result) // either this paragraph or ...
{
echo Incorrect User Credentials!";
exit;
}
elseif (password_verify($password, $row['passwords']))
{
if($row['accounts_activations_statuses'] == '0')
{
echo "You have not activated your
account yet! Check your email for instructions
.";
exit;
}
}
else
{
//If 'Remember Me' check box is checked then set the
cookie.
//if (isset($_POST['login_remember']) &&
$_post['login_remember'] == "on")
{
setcookie("login_username", $username, time()+
(10*365*24*60*60));
}
else
{
//If Cookie is available then use it to auto log
user into his/her account!
if (isset($_COOKIE['login_username']))
{
setcookie("login_username","","");
}
}
$_SESSION["user"] = $username;
header("location:home.php?user=$username");
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php $site_name?> Member Login Page</title>
<meta charset="utf-8">
</head>
<body>
<div class = "container">
<form method="post" action="">
<center><h3><?php $site_name ?> Member Login Form</h3></center>
<div class="text-danger">
<div class="form-group">
<center><label>Username/Email:</label>
<input type="text" placeholder="Enter Username" name="login_username_or_email" value="<?php if(isset($_COOKIE["login_username_or_email"])) echo $_COOKIE["login_username_or_email"]; ?>"</center>
</div>
<div class="form-group">
<center><label>Password:</label>
<input type="password" placeholder="Enter password" name="login_password" value="<?php if(isset($_COOKIE["login_password"])) echo $_COOKIE["login_password"]; ?>"></center>
</div>
<div class="form-group">
<center><label>Remember Login Details:</label>
<input type="checkbox" name="login_remember" /></center>
</div>
<div class="form-group">
<center><input type="submit" name="login_submit" value="Login" class="button button-success" /></center>
</div>
<div class="form-group">
<center><font color="red" size="3"><b>Forgot your password ?</b><br>Reset it here!</font></center>
<center><font color="red" size="3"><b>Not registered ?</b><br>Register here!</font></center>
</form>
</div>
</body>
</html>
</pre>

Apart from all the syntax shenanigans, you're not returning the password from the query:
$stmt = mysqli_prepare($conn, "
SELECT usernames FROM users WHERE usernames = ?"
);
So it will be null

You need to fetch password column also from db
if(strpos("$username_or_email", "#") === true)
{
$email = $username_or_email;
$username = "";
$stmt = mysqli_prepare($conn, "SELECT emails,passwords FROM users
WHERE emails = ?"); //<---Add passwords in select
mysqli_stmt_bind_param($stmt, 's', $email);
}
else
{
$username = $username_or_email;
$email = "";
$stmt = mysqli_prepare($conn, "SELECT usernames,passwords FROM
users WHERE usernames = ?"); //<---Add passwords in select
mysqli_stmt_bind_param($stmt, 's', $username);
}

Related

How to change this part of code as PHP prepared statement?

Statement
In login_check.php, it worked but I would like to change it into the prepared statement.
login.php
<body>
<div class="container">
<h1>Please Log In to the System</h1>
<form method="post" action="login_check.php">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<button type="submit" name="login" value="Log In">Log In</button>
</form>
</div>
</body>
login_check.php
<body>
<?php
//Establish connection
include 'connection.php';
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$sql = "SELECT * FROM admins WHERE admin_username = '".mysqli_real_escape_string($conn, $_POST['username'])."' and admin_password = '".mysqli_real_escape_string($conn, $_POST['password'])."'";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_array($query);
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if(!$result) //Username or Password is invalid!
{
?>
<div class="container">
<h1>Username or Password is invalid!</h1>
<form method="post" action="login.php">
<button type="submit">Back</button>
</form>
</div>
<?php
}
else //Username and Password are valid!
{
$_SESSION["admin_id"] = $result["admin_id"];
$_SESSION["admin_username"] = $result["admin_username"];
session_write_close();
header("location:front.php");
}
$conn->close();
?>
</body>
To change to prepared statements, you just need to
replace variables in your query with a ?
prepare the query
bind variables to the parameters
execute the statement
For your code that would look like this:
$sql = "SELECT * FROM admins WHERE admin_username = ? and admin_password = ?";
$stmt = $conn->prepare($sql) or die($conn->error);
$stmt->bind_value("ss", $_POST['username'], $_POST['password']);
$stmt->execute() or die($stmt->error);
$result = $stmt->get_result();
Note that you should not be storing passwords in plain text in your database. Please look into PHPs password_hash and password_verify functions to properly handle your passwords. You would use password_hash when storing the password in the database, and then your code for verifying the user would look something like:
$sql = "SELECT * FROM admins WHERE admin_username = ?";
$stmt = $conn->prepare($sql) or die($conn->error);
$stmt->bind_value("s", $_POST['username']);
$stmt->execute() or die($stmt->error);
$result = $stmt->get_result() or die($stmt->error);
$row = $result->fetch_array();
if (!$row|| !password_verify($_POST['password'], $row['admin_password']) {
// invalid username or password
login_check.php
<?php
//Establish connection
include 'connection.php';
$sql = "SELECT * FROM admins WHERE admin_username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array())
{
$hash = password_hash($_POST['password'],PASSWORD_DEFAULT);
mysqli_query($conn,"UPDATE admins SET admin_password = '$hash' WHERE admin_id='{$row['admin_id']}");
}
if(!$row || !password_verify($_POST['password'],$row['admin_password']))
{
?>
<div class="container">
<h1>Username or Password is invalid!</h1>
<form method="post" action="login.php">
<button style="font-size: 30px" type="submit" class="btn btn-dark"><b>Back</b> <i class="fas fa-arrow-alt-circle-left"></i></button>
</form>
</div>
<?php
}
else
{
$_SESSION["admin_id"] = $result["admin_id"];
$_SESSION["admin_username"] = $result["admin_username"];
session_write_close();
header("location:front.php");
}
$stmt->close();
$conn->close();
?>
</body>
There is no syntax error shown up but I think there are some mistakes in
=> mysqli_query($conn,"UPDATE admins SET admin_password = '$hash' WHERE admin_id ='{$row['admin_id']}");
=> if(!$row || !password_verify($_POST['password'],$row['admin_password']))
Form this code, the result is it always returns as username or password is invalid, even I put the valid ID and Password.

Notice: Trying to get property 'num_rows' of non-object

I'm reworking a login form to PDO based with OOP in mind. And I am running into the error given above. So I have two files one is an login.php and one is an included file called functions.inc.php
The code for the login.php is as follows.
<?php
include_once("includes/functions.inc.php");
// get username and password from $_POST
if(!empty($_POST)){
$username = $_POST['email'];
$password = $_POST['password'];
// check if a user can login (function)
if(canilogin($username, $password)){
session_start();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
header('Location: index.php');
}
else{
$error = true;
// if no -> $error tonen
}
}
?><!DOCTYPE html>
<html lang="en">
<body class="login">
<div class="grid container_login">
<div class="login_grid">
<form class="form_login" action="" method="post">
<?php if( isset($error) ): ?>
<div class="form__error">
<p>
Sorry, we can't log you in with that email address and password. Can you try again?
</p>
</div>
<?php endif;?>
<div>
<label for="email">EMAIL</label><br/>
<input type="text" id="email" name="email" placeholder="Lucasdebelder#snapshot.be" required>
</div>
<div>
<label for="password">PASSWORD</label><br/>
<input type="password" id="password" name="password" placeholder="Atleast 8 characters" required>
</div>
<div>
<input type="submit" value="LOG IN" class="btn_login">
</div>
<p class="center_align">Or</p>
<br/>
<a class="center_align" href="register.php">Register here.</a>
</form>
</div>
</body>
</html>
And the functions.inc.php where the error is happening, to be precise it happens at if($result->num_rows != 1){.
Also the first few lines were the once that worked before but that is done with real escape string to secure against SQL inject but it's kinda a wacky way to do and I decided to try to rework it to PDO.
<?php
function canilogin( $username, $password){
/* THIS IS THE OLD WAY THAT WORKED/WORKS
$conn = new mysqli("localhost", "root", "root", "snapshot");
$query = "select * FROM users WHERE email='".$conn->real_escape_string($username). "'";
$result = $conn->query($query);
*/
$conn = new PDO('mysql:host=localhost; dbname=snapshot', 'root', 'root');
//$query = "select * FROM users WHERE email='".$conn->real_escape_string($username). "'";
$statement = $conn->prepare("select * from users where email = :username");
$statement->bindValue(':username', $username);
$statement->execute();
$result = $statement->execute();
if($result->num_rows != 1){
return false;
}
$user = $result->fetch_assoc();
if(password_verify($password, $user['password'])){
return true;
}
else{
return false;
}
}
?>
The reason you are having the issue is that $result is not correct. Once $statement->execute(); is executed it becomes a PDOStatement object.
First of all remove $result = $statement->execute(); and try
if($statement->rowCount() != 1){
return false;
}
$user = $statement->fetch();
if(password_verify($password, $user['password'])){
return true;
}
else{
return false;
}

PHP, MySQl query not running

Got this error. Please can anyone help. I am a beginner at this.
Undefined variable: mysqli in C:\xampp\htdocs\final\register.php on line 20
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\final\register.php:20 Stack trace: #0 {main}
thrown in C:\xampp\htdocs\final\register.php on line 20
What do we need to do in order to validate the html form with some validation and how can we put the submitted details into the database table ?
This is the code of
Register.php
<?php
include "header.php";
// Include config file
require_once 'dbconfig.php';
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM signup WHERE username = ?";
if($stmt = $mysqli->prepare($conn,$sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
// store result
$stmt->store_result();
if($stmt->num_rows == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Validate password
if(empty(trim($_POST['password']))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST['password'])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST['password']);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = 'Please confirm password.';
} else{
$confirm_password = trim($_POST['confirm_password']);
if($password != $confirm_password){
$confirm_password_err = 'Password did not match.';
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO signup (username, password) VALUES (?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if($stmt->execute()){
// Redirect to login page
header("location: login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{
width: 350px;
padding: 20px;
margin: 10px 10px 10px 10px;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username"class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</div>
</body>
</html>
if($stmt = mysqli_prepare($conn, $sql)){}
This line shows error. What is binding and how to use it?
Login.php
<?php
include 'header.php';
// Include config file
require_once 'dbconfig.php';
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = 'Please enter username.';
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST['password']))){
$password_err = 'Please enter your password.';
} else{
$password = trim($_POST['password']);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT Username, Password FROM login WHERE Username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "a", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
/* Password is correct, so start a new session and
save the username to the session */
session_start();
$_SESSION['username'] = $username;
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = 'The password you entered was not valid.';
}
}
} else{
// Display an error message if username doesn't exist
$username_err = 'No account found with that username.';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username"class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>
register_val.php
<?php
require_once('dbconfig.php');
// function for email validation
function is_valid_email($email)
{
if (empty($email)) {
echo "Email is required.";
return false;
} else {
$email = test_input($email);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
return false;
}
// now check if the mail is already registered
$slquery = "SELECT 2 FROM signup WHERE Email = '$email'";
$selectresult = mysql_query($slquery);
if(mysql_num_rows($selectresult)>0) {
echo 'This email already exists.';
return false;
}
// now returns the true- means you can proceed with this mail
return true;
}
// function for password verification
function is_valid_passwords($password,$confirm_password)
{
// Your validation code.
if (empty($password)) {
echo "Password is required.";
return false;
}
else if ($password != $confirm_password) {
// error matching passwords
echo 'Your passwords do not match. Please type carefully.';
return false;
}
// passwords match
return true;
}
// function for creating user
function create_user($email, $password, $confirm_passwordpassword)
{
$query = "INSERT INTO `singup` (email, password, confirmpassword) VALUES ('$email', '$password', '$cpassword')";
$result = mysql_query($query);
if($result){
return true; // Success
}else{
return false; // Error somewhere
}
}
// Code execution starts here when submit
if (isset($_POST['email']) && isset($_POST['password'])){
// Reading form values
$email = $_POST['email'];
$password = $_POST['password'];
$confirm_password = $_POST['confirmpassword'];
if (is_valid_email($email) && is_valid_passwords($password,$confirm_password))
{
if (create_user($email, $password, $cpassword)) {
echo 'New User Registered Successfully.';
}else{
echo 'Error Registering User!';
}
}
// You don't need to write another 'else' since this is the end of PHP code
?>
dbconfig.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername; dbname = 'car sale' ", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Have you created object $mysqli?
$mysqli = new Mysqli("host","db user","db password","db name");
Put it on Register.php before you call $mysqli
mysqli and PDO are different. Please refer https://www.w3schools.com/php/php_mysql_connect.asp
Your dbconfig.php will look like
<?
$host="127.0.0.1";
$port=3306;
$socket="";
$user="user";
$password="password";
$dbname="dbname";
$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
if($mysqli!=null){
//echo "Mysql connected. Yeah!<br/>";
$mysqli->close();
}
?>
Honestly this is a mess, you have
$conn = new PDO("mysql:host=$servername; dbname = 'car sale' ", $username, $password);
Then
$mysqli->prepare($conn,$sql)
Then (deprecated and removed in PHP7+)
$result = mysql_query($query);
And
$query = "INSERT INTO `singup` (email, password, confirmpassword) VALUES ('$email', '$password', '$cpassword')";
And
$slquery = "SELECT 2 FROM signup WHERE Email = '$email'";
SQLInjection issues. 3 different databases drivers. Um Start over?....
I would start by getting rid of all that DB junk, and use only one of them (Preferably PDO. :-) ).
Hey it does look like you go the login done fairly well, not querying the password, using a secure hash compare function. Checking for 1 and only one result. That's all good. The rest ... not so much.
It needs a lot of cleanup done, this is all simple stuff, but it's beyond the scope of one question.
Once you clean up the DB stuff you may find that this error evaporates... Because you are confused as to how you are connecting to the DB.
To be frank, it looks like a lot of Copy and pasted code. There is nothing wrong with that, but you have to understand what the code does on some level. Code is like handwriting, you can tell how well someone knows the language by how they write the code. I see maybe 4 different levels of coders at work here.

PHP Prepared statements - Failing to retrieve the string from the database

I'm still fairly new to the prepared statements because it was brought to my attention by another user. I've been able to create a registration function that properly prepares the statement, binds it and then executes it. It goes into the database just fine. However, I'm not sure I understand how the login part would work. I'm trying to fetch a row and the result I keep getting is "1" but not the row + data inside the row. Any advice?
Database:
login.php (where the form is located)
<form id="loginform" class="form-horizontal" role="form" action="" method="post">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="Lusername" placeholder="Username or Email">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="Lpassword" placeholder="Password">
</div>
<div class="input-group">
<div class="checkbox">
<label>
<input id="login-remember" type="checkbox" name="remember" value="1"> Remember me
</label>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button id="btn-login" type="submit" class="btn btn-success"><i class="icon-hand-right"></i>Submit</button>
</div>
</div>
</form>
script:
<script type="text/javascript">
$(function() {
$("#loginform").bind('submit',function() {
var username = $('#login-username').val();
var password = $('#login-password').val();
$.post('scripts/loginFunction.php',{username:username, password:password}, function(data){
$('#signupsuccess').show();
}).fail(function(){{
$('#signupalert').show();
}});
return false;
});
});
</script>
loginFunction.php
<?php
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT `Username`, `Password` FROM `users` WHERE `Username` = ?");
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
/*if($stmt->num_rows == 1){
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
// here is where you could verify the password
if(password_verify($password, $row['Password'])) {
// good password
echo 'all good!';
}
} else {
//echo "failed to find row";
}*/
?>
loginFunction.php that does work and queries the database properly
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($query);
if($result->num_rows == 1){
$row = mysqli_fetch_array($result);
if(password_verify($password, $row['Password'])){
echo "Login successful!";
}
else{
echo "Login failed.";
}
}
EDIT: Here is the code you should use. Note how $stmt is carried throughout:
$stmt = $conn->prepare("SELECT `Username`, `Password` FROM `users` WHERE `Username` = ?");
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
/*if($stmt->num_rows == 1){
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
// here is where you could verify the password
if(password_verify($password, $row['Password'])) {
// good password
echo 'all good!';
}
} else {
//echo "failed to find row";
}*/
I have resolved the issue. When I went to fetch, I needed to store it in a separate variable than the one that the user is storing their entered password into. This can be reflected in the code below:
<?php
require 'connection.php';
$username = $_POST['username'];
$password = $_POST['password'];
$dbusername = ""; //These two being the new variables
$dbpassword = "";
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT Username, Password FROM users WHERE Username = ?;");
$stmt->bind_param('s', $username);
$stmt->execute();
if($stmt->execute() == true){
$stmt->bind_result($dbusername, $dbpassword);
$stmt->fetch();
if(password_verify($password, $dbpassword)) {
echo 'successful';
}
else{
echo 'failed';
}
}
else{
echo 'failed';
}
?>

Php/Mysql login authentication

I am unable to authenticate using Php/mysql, using the following method. I used a form in order to login. Please check the following and help me out?
form.php
<html>
<body>
<h2>Authentication</h2>
<form action="login.php" method="post">
<label>Userid :</label>
<input type="text" id="userid" name="userid" >
<label>Password :</label>
<input type="password" id="password" name="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</body>
</html>
login.php
<?php
$message="";
if(count($_POST)>0) {
mysql_connect("localhost", "root", "kami123")or
die(mysql_error());
mysql_select_db("ccmsdb") or die(mysql_error());
$result = mysql_query("SELECT *FROM client WHERE
userid='" . $_POST["userid"] . "' AND
password = '". $_POST["password"]."'");
$count = mysql_num_rows($result);
if($count==0) {
$message = "Invalid Username or Password!";
} else {
$message = "You are successfully authenticated!";
}
}
?>
Besides what's already mentioned in the comments, you are missing a space in the query:
SELECT *FROM client WHERE
should be
SELECT * FROM client WHERE
Why don't you try PDO? MySQL functions are deprecated.
$err="";
(isset($_POST['email'], $_POST['pass'])) {
$email = $_POST['email'];
$pass = $_POST['pass'];
if(!empty($email) && !empty($pass)) {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
$err = 'Invalid email format.';
}
$dbc = new PDO('mysql:host=YOUR HOST;dbname=YOUR DBNAME', 'YOUR USERNAME', 'YOUR PASSWORD');
$stmt = $dbc->prepare("SELECT id, name, pass FROM client WHERE email =:email LIMIT 1");
$stmt -> bindValue(':email', $email);
$stmt -> execute();
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ){
if(password_verify($pass, $row['pass'])) {
//Logged In
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
header('Location:logged_in_user_page.php');
... bla bla ...
}else {
// Not Logged In
header('Location:not_logged_in_user_page.php');
}
}
}else {
$err = 'You have to provide an email and a password!';
}
}

Categories