How to apply the bcrypt also how to fetch data - php

When I try to login it doesn't display any information, it didn't get the data in database.
if($_SERVER['REQUEST_METHOD']=='POST'){
//filter this variable for security
$username = strip_tags(mysqli_real_escape_string($conn, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($conn, trim($_POST['password'])));
$stmt = $conn->prepare("SELECT id FROM students WHERE s_id = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$user = $stmt->fetch();
if($user == FALSE) {
die("Incorrect");
}else {
$password_hash = $user['password'];
$validPassword = password_verify($password, $password_hash);
if($validPassword){
echo "success";
} else{
//$validPassword was FALSE. Passwords do not match.
echo 'Incorrect username / password combination!<br/>';
echo $user['password'];
}
}
}

Your query only selects the id. Change your query to select your id and password.
$stmt = $conn->prepare("SELECT * FROM students WHERE s_id = ?");
Then you will have your hashed password $user['password'] in the results.

I'd be tempted to wrap everything in a try/catch block and raise exceptions at key points to determine where the code breaks. Also I think the result from the query should be bound to a variable prior to fetching the results using $stmt->bind_result
When using a prepared statement I'd suggest that you do NOT use mysqli_real_escape_string nor use trim as it would be perfectly valid for a password to start or end with a space - the database engine will process the statement in a manner that is safe.
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['username'],$_POST['password']) ){
try{
$args=array(
'username' => FILTER_SANITIZE_STRING,
'password' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$stmt = $conn->prepare("select `password` from `students` where `s_id` = ?");
if( $stmt ){
$stmt->bind_param( "s", $username );
$result = $stmt->execute();
if( $result ){
/* There should be only 1 record - bind to a variable */
$stmt->bind_result( $pwdhash );
/* fetch the results of the query */
$stmt->fetch();
/* is the password correct? */
$validpassword = password_verify( $password, $pwdhash );
echo $validpassword ? 'Success' : 'Error: Incorrect username or password';
$stmt->close();
} else {
throw new Exception('No results returned');
}
} else {
throw new Exception('failed to prepare sql query');
}
} catch( Exception $e ){
exit( $e->getMessage() );
}
}

Related

prepared statements in if else statement

Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();

Php MySql Select count with prepared statment return always 1

I'm using this method to get make a login Web Service:
function redeem() {
if (isset($_POST["user"]) && isset($_POST["pass"]) && isset($_POST["computer"])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$computer = $_POST['computer'];
$galNumb = "SELECT COUNT(*) FROM Useres WHERE username = ? AND password = ?";
$stmt = $this->db->prepare($galNumb);
$stmt->bind_param('ss', $user, $pass);
$gNumb = $stmt->execute();
$result = array(
"success" => "true",
);
$this->sendResponse(200, $gNumb);
return true;
}
$this->sendResponse(400, 'Invalid request');
return false;
}
The problem is that $gNumb always return 1 even when the sql table not contain the username and the password. Any idea what can be the problem?
You forgot to fetch results:
...
$stmt->bind_param('ss', $user, $pass);
if ($stmt->execute()) {
$stmt->bind_result($gNumb);
$stmt->fetch();
} else {
$gNumb = 0;
}
...

using mysqli prepared stmt within "if" condition with "||" and "&&" operator

I am just learning mysqli prepared statements and now i have run into a problem and could not get a way out of it. It is the registration form and takes in "username" "email" and "password". if username and email already exists in the database then it doesnot allow registeration. i've used post method and the code is as,
//validating email
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL) === true) {
echo "invalid email";
exit();
}
//valid email
else{
//prepared query
$query_name = "SELECT * FROM users WHERE user_name = ?";
$query_email = "SELECT * FROM users WHERE user_email = ?";
//prepared statements
$stmt_name = mysqli_prepare($conn, $query_name);
$stmt_email = mysqli_prepare($conn, $query_email);
//if bind failure
if((!mysqli_stmt_bind_param($stmt_name, "s", $user_name)) && (!mysqli_stmt_bind_param($stmt_email, "s", $user_email))){
echo "bind unsuccessfull";
exit();
}
else{
//if execution fails
if( !mysqli_stmt_execute($stmt_name) && !mysqli_stmt_execute($stmt_email)){
echo "stmt execution failed";
exit();
}
//else if execution success
else{
$result_name = mysqli_stmt_store_result($stmt_name);
$result_email = mysqli_stmt_store_result($stmt_email);
//rows
$row_name = mysqli_stmt_num_rows($stmt_name);
$row_email = mysqli_stmt_num_rows($stmt_email);
echo $row_name;
echo $row_email;
}
}
}
it looks like the first part before && in if condition works and the second doesnot work at all. i have tried registering it with existing "email" in the database but the result is still 0.
the connection is fine and works!
Any help will be appreciated>
Instead of doing so much complex code, use single query to do your job
//validating email
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL) === true) {
echo "invalid email";
exit();
}
else{
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE user_name = ? OR user_email = ?");
mysqli_stmt_bind_param($stmt, 'ss', $user_name, $user_email);
if( !mysqli_stmt_execute($stmt)){
echo "stmt execution failed";
exit();
}else{
$result_name = mysqli_stmt_store_result($stmt_name);
$result_email = mysqli_stmt_store_result($stmt_email);
//rows
$row_name = mysqli_stmt_num_rows($stmt_name);
$row_email = mysqli_stmt_num_rows($stmt_email);
echo $row_name;
echo $row_email;
}
}
$query_name = "SELECT * FROM users WHERE user_name = ? OR user_email = ?";
you don't need to check the condition twice at same time.If someone will login through email or username then this query will check for both username and email.
I would be tempted to roll both queries together using an or condition in conjunction with a try/catch block so that you can throw exceptions at certain stages if a condition is not met.
if( !isset( $user_email ) or !filter_var( $user_email, FILTER_VALIDATE_EMAIL ) === true ) {
exit("invalid email");
} else {
try{
if( isset( $user_name, $user_email ) ){
$sql='select `user_name`,`user_email` from `users` where `user_name` = ? or user_email = ?'
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ss', $user_name, $user_email );
$result=$stmt->execute();
if( $result ){
$stmt->store_result();
if( $stmt->num_rows == 1 ){
/* user name &/or email already exists */
$stmt->bind_result( $name, $email );
$stmt->fetch();
printf('whoohoo! - found user "%s" with email "%s"', $name, $email );
} else {
/* no record for username or email*/
/* sql query to insert new user */
}
$stmt->free_result();
$stmt->close();
} else {
throw new Exception('sql query failed to return any results');
}
} else {
throw new Exception('unable to prepare sql');
}
} else {
throw new Exception('username &/or email are missing');
}
}catch( Exception $e ){
echo $e->getMessage();
}

PHP code for checking id with their specific password

I've created a login activity and there are two edittext ids and passwords. I have a PHP code which checks the user with their id and password. If both are correct then it transfers to the other activity, but here I want a PHP code which checks the id with their specific password. If the user enters a correct id but enters an incorrect password, then it should produce an error "pls enter correct password".
Please suggest me a correct PHP code for this.
<?php
require "r_connect.php";
if($_SERVER['REQUEST_METHOD']=='POST')
{
$rollno=$_POST['rollno'];
$password=$_POST['password'];
$sql = "SELECT * FROM registration_user WHERE rollno = '$rollno' AND password='$password'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo 'Success';
}
else
{
echo 'Error';
}
}
?>
Try below code for PHP:
<?php
require "r_connect.php";
if($_SERVER['REQUEST_METHOD']=='POST')
{
$rollno = $_POST['rollno'];
$password = $_POST['password'];
$sql = "SELECT password FROM registration_user WHERE rollno = '$rollno'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
if(mysqli_num_rows($check) > 0)
{
if($check["password"] == $password){
echo 'Success';
}else{
echo 'pls enter correct password';
}
}
else
{
echo 'Invalid id';
}
}
?>
You can also refer this tutorial for more information
Split your SQL statement into to, at first query WHERE rollno = '$rollno', if found go on and query WHERE rollno = '$rollno' AND password = '$password', if everything's correct go on, if first statement fails user is not found, if second query fails, the user is found but password is not matching, this is your desired case.
When writing an authentication flow you can keep following things in mind :
validate your input data well
when interacting with Select queries use prepared statements whenever possible
use sha1 and md5 combinations on the password string to store in the database and comparisons.
I have tried to implement these things in the following code, of course there's always scope for improvement
function checkRollno($conn, $rollno)
{
$stmt = mysqli_stmt_init($conn);
$prepareQuery = "SELECT count(*) FROM tablename WHERE rollno = ?";
//Prepared Statements
if( mysqli_stmt_prepare($stmt, $prepareQuery ) )
{
// Bind params
mysqli_stmt_bind_param($stmt, 'i', $rollno);//i is for integer
/* execute query */
mysqli_stmt_execute($stmt);
/* Fetch Result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
/* close statement */
mysqli_stmt_close($stmt);
if( count($row) < 1 )
return false;
else
return true;
}
else
return false;
}
function checkUserExists($conn, $rollno, $pass)
{
$stmt = mysqli_stmt_init($conn);
$prepareQuery = "SELECT count(*) FROM tablename WHERE rollno = ? AND password= ?";
//Compare sha1 of md5 of your password (You should not store or check against exact password strings)
$pass = sha1(md5($pass));
//Prepared Statements
if( mysqli_stmt_prepare($stmt, $prepareQuery ) )
{
// Bind params
mysqli_stmt_bind_param($stmt, 'is', $rollno, sha1(md5($pass)));// s is for strings
/* execute query */
mysqli_stmt_execute($stmt);
/* Fetch Result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
/* close statement */
mysqli_stmt_close($stmt);
if( count($row) < 1 )
return false;
else
return true;
}
else
return false;
}
//Main Block
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if( isset($_POST['rollno']) && $_POST['rollno'] != '' )
$rollno = $_POST['rollno'];
if( isset($_POST['password']) && $_POST['password'] != '' )
$pass = $_POST['password'];
$res = checkRollno($conn, $rollno);
if( $res )//rollno exists
{
if( checkUserExists( $conn, $rollno, $pass ) )
die('authenticated');//Authenticated
else
die('denied');//Wrong password
}
else//rollno doesn't exist
{
//code to reflect wrong id does not exist
}
}
I am sure you can use better function names :)
Prepared Statements
Your code could look like this :
$sql = "SELECT * FROM registration_user WHERE rollno = '$rollno'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
Then you can do checks :
if(mysqli_num_rows($check) > 0)
{
if($check['password']===$password){
//id and pass correct
}else{
// id correct , but bad password
}
}else
{
echo 'Invalid id';
}

Check if email already exist [duplicate]

This question already has answers here:
Check if email already exists in database
(4 answers)
Closed 6 years ago.
How do I check if the email already exist in the database and deny the registration?
MySQL was the one taught to me and I'm currently on a wall using MySQLi.
Here is the code that I'm currently working on using MySQLi:
<?php
$cookie_name = "loggedin";
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarcaps";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['login']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$cookie_value = $user;
setcookie($cookie_name, $cookie_value, time() + (180), "/");
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if (isset($_POST['register']))
{
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "INSERT INTO users (id, email, username, password) VALUES ('','$email', '$user', '$phash');";
$result = mysqli_query($conn, $sql);
}
?>
Despite using mysqli your code is still vulnerable to sql injection as you directly embed variables in the sql statements - use prepared statements to avoid nasty surprises. The following is not tested but should show how you can use prepared statements. There are better ways of hashing the password - such as password_hash and also password_verify though these are not available in PHP versions prior to 5.5
$response=array();
$cookie_name='loggedin';
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = '';
$dbname = 'scholarcaps';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
if( isset( $_POST['login'] ) ) {
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1( sha1( $pass . "salt" ) . "salt" );
$sql='select `username`, `password` from `users` where `username`=? and `password`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$stmt->bind_param( 'ss', $username, $phash );
$result=$stmt->execute();
if( !$result ) $response[]='Query failed';
$stmt->store_result();
$stmt->bind_result( $name, $pwd );
$stmt->fetch();
if( $stmt->num_rows()==0 ) $response[]='No such user';
else {
$stmt->free_result();
$stmt->close();
$db->close();
setcookie( $cookie_name, $user, time() + 180, "/" );
exit( header( "Location: personal.php" ) );
}
$stmt->free_result();
$stmt->close();
$db->close();
/* show errors */
if( !empty( $response ) ){
echo '<ul><li>',implode('</li><li>',$response),'</li></ul>';
}
}
} elseif( $_POST['register'] ){
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$phash = sha1( sha1( $pass . "salt" ) . "salt" );
/* Does the email address already exist? */
$emailfound=false;
$sql='select `email` from `users` where `email`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$stmt->bind_param('s',$email);
$result=$stmt->execute();
if( $result ){
$stmt->store_result();
$stmt->bind_result( $emailfound );
$stmt->fetch();
$stmt->free_result();
}
}
if( $emailfound ){
echo 'Sorry, that email address already exists in our database. Please try again with a different address.';
$stmt->close();
$db->close();
} else {
/* the `id` should be automatically generated I assume - hence being omitted here */
$sql='insert into `users` (`email`, `username`, `password`) values (?,?,?);';
$stmt=$db->prepare( $sql );
if( $stmt ){
$stmt->bind_param( 'sss', $email, $username, $phash );
$result=$stmt->execute();
$stmt->free_result();
$stmt->close();
$db->close();
if( $result ) header('Location: login.php');
else{
/* failed to register the user */
}
}
}
}
I solved this problem by setting my email column with unique attribute. After the registration submit you can catch the mysqli_errno(). So you will see if there is a duplicate entry.
You will save a check-query with this solution.
If you don't want to match the email, you just want to make sure an email address exists, you could...
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash' AND email<>'';";
or, to specify a minimum length...
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash' AND LEN(email) > 0;";
Use this php function for get record count in db
$count=mysqli_num_rows($result)
after check it more than 0 or not
Try this,
add this code after sha1
$result = mysql_query("select COUNT(id) from users where email='".$email."'");
$count = mysqli_num_rows($result);
if($count > 0){
echo "email exist";
}else
{
$sql = "INSERT INTO users (id, email, username, password) VALUES ('','$email', '$user', '$phash');";
$result = mysqli_query($conn, $sql);
}

Categories