PHP MYSQLI query error? - php

Hey This is my login script, using PHP5 and MYSQLi, I just had help spotting errors in my query, but still it will not let me login, even though the username and password are correct and in the database, it just keeps returning the error: your username and password do not match any in our db. But I know they do lol...could any body spot the problem?
//Check if the form has been submitted
if (isset($_POST['login']))
{
//Check if username and password are empty
if ($_POST['username']!='' && $_POST['password']!='')
{
//Create query to check username and password to database
$validate_user = $mysqli->query('SELECT id, username, password, active FROM users WHERE = username = "'.$mysqli->real_escape_string($_POST['username']).'" AND password = "'.$mysqli->real_escape_string(md5($_POST['password'])).'"');
//We check if the query returns true
if ($validate_user->num_rows == 1)
{
$row = $validate_user->fetch_assoc();
//Check if the user has activated there account
if ($row['activated'] == 1)
{
$_SESSION['id'] = $row['id'];
$_SESSION['logged_in'] = true;
Header('Location: ../main/index.php');
}
//Show this error if activation returns as 0
else {
$error = '<p class="error">Please activate your account.</p>';
}
}
//Show this error if the details matched any in the db
else {
$error = '<p class="error">Your username and password are not in our database!</p>';
}
}
//Show this error if the username and password field have not been entered
else {
$error = '<p class="error">Please enter your username and password.</p>';
}
}

Instead of
SELECT ... FROM users WHERE = username = ...
It should be
SELECT ... FROM users WHERE username = ...
If you keep getting problems like this, try storing the query in a variable and echo it, so you can copy-paste it into your database management tool and see if there are any query errors.

To make it most reliable way, I'd suggest to trigger this error according to main error handling settings:
//just in sake of readability
$user = $mysqli->real_escape_string($_POST['username']);
$pass = $mysqli->real_escape_string(md5($_POST['password']));
$sql = "SELECT id, username, password, active FROM users
WHERE username = '$user' AND password = '$pass'";
$res = $mysqli->query($sql) or trigger_error(mysqli->error.$sql);
note that trigger_error function. it will bring error message to the standard error output. On the development PC it will be browser's screen or a log file on the production server.

Related

Hashed Password Check Issue

I am working on a Forgot-Password system where users are emailed a ForgotKey code to enter to access a reset password screen. When this ForgotKey is entered into the database, it is hashed. I used a similar system for my signup page and it's working correctly. I copied most of the code over from that system and now I am getting an error that the user's inputted password does not match the hashed password in the database. Am I using the correct password_verify code for this scenario?
$Email = $_SESSION['PWResetEmail'];
$ForgotKey = $_POST['ForgotKey'];
$ForgotKeySQL = "SELECT Email, ForgotKey, ForgotTime, UserID FROM UserTable WHERE Email = ?";
$ForgotKeySTMT = $conn->prepare($ForgotKeySQL);
$ForgotKeySTMT->bind_param("s", $Email);
$ForgotKeySTMT->execute();
$ForgotKeyRESULT = $ForgotKeySTMT->get_result(); // get the mysqli result
while ($ForgotKeyROW = $ForgotKeyRESULT->fetch_assoc()) {
// A: If password matches DO NOT hash, then send user back to forgot.php to retry
$ForgotKeyCheck = password_verify($ForgotKey, $ForgotKeyROW['ForgotKey']);
if ($ForgotKeyCheck == false) { // <----- code is failing here
$ForgotKeySTMT->free_result();
$ForgotKeySTMT->close();
header("Location: ../forgot.php?4");
exit();
}
// A: If password matches hash, then let user pass to next step of forgot password system.
else if ($ForgotKeyCheck == true) { // <---- I want this line to be true
$ForgotTimeFINAL = $ForgotKeyROW['ForgotTime'];
$UserIDTemp = $ForgotKeyROW['UserID'];
$_SESSION['UserIDTemp'] = $UserIDTemp;
$_SESSION['ForgotKey'] = $ForgotKeyROW['ForgotKey'];
$ForgotKeySTMT->free_result();
$ForgotKeySTMT->close();
header("Location: ../forgot.php?3");
exit();
}
else {
$ForgotKeySTMT->free_result();
$ForgotKeySTMT->close();
header("Location: ../forgot.php?2");
exit();
}
}

Error message not showing if the user enters incorrect information

I am trying to display the error at the end if the use doesn't enter the correct combination of their log in. However, the error message is not showing when I enter the wrong password or email. Any suggestions
<?php
include ("connect.php");
if (isset($_POST["user_login"]) && (isset($_POST["user_pass"]))){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
$user_type = $row['account'];
}
$_SESSION["user_login"] = $login_user;
// check the user type and redirect according to it
if($user_type == "Student"){
$student_page = "profile_student.php";
header( "Location:{$student_page}" );
} elseif ($user_type == "Landlord"){
$landlord_page = "landlord_profile.php";
header( "Location:{$landlord_page}" );
} elseif ($user_type == "Administrator"){
$admin_page = "admin_profile.php";
header( "Location:{$admin_page}" );
}else {
$refresh_page = "sign_up.php";
header( "Location:{$refresh_page}" ); // refresh page
echo "You have entered an incorrect email or password. Please try again.";
}
}
}
?>
you redirect user if input data is wrong and only after that you try to echo message, thats not how that works. read about headers in php_manual. probably the best way here, is to store error message in session and after redirect check if session error message exists
else {
$refresh_page = "sign_up.php";
$_SESSION['error'] = "your error message"
header( "Location:{$refresh_page}" ); // refresh page
}
in sign_up.php file check if error message exists in session
if(isset($_SESSION["error"])){
echo $_SESSION["error"];
unset($_SESSION["error"]);
}
maybe you should correct this code a little bit))
use unset cause' after you show the message it should be removed from session, in other case if you fail for example 5 times, it will show 5 messages)) also make sure that session is started session_start() hope it helps:)
You only display the error when $user_type doesn't match any of your expected types.
You need a second else after your if ($check_user==1){ block to handle the case where a user with that email or password doesn't exist.

Issue with Sign in form in PHP

I am trying to use the below code to create a login form. The problem being after registration when I am trying to login, getting an error message "Username or Password don't match" even though email & password are correct. I tried "$num <=1" and allows me to log in but obviously it is not authenticating the login details in that case. Any help will be appreciated.Most importantly this code is working fine on a local server like XAMPP but problem starts when using a host server like hostgator (no issue to connect with the server).
<?php
session_start(); // Starting Session
#Database connection
include('../config/connection.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit']))
{
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = '<p class="alert alert-danger">One or either field is missing</p>';
}
else
{
// Define $username and $password
$email=$_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection for Security purpose
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
// SQL query to fetch information of registerd users and finds user match.
$q = "SELECT * FROM users WHERE email = '$email' AND password = md5(SHA1('$password'))";
$r = mysqli_query($dbc, $q)or die(mysqli_error());
$num = mysqli_num_rows($r);
if($num ==1){
$_SESSION['username'] = $email;
header('Location:Index.php');
} else {
$error = '<p class="alert alert-danger">Username or Password don\'t match</p>';
}
mysqli_close($dbc); // Closing Connection
}
}
?>
in your query the $password should not be between the quotes, cause then it will seek for the string instead of the value of the variable.
$q = "SELECT * FROM users WHERE email = '$email' AND password = 'md5(SHA1($password))'";
make sure your password is hashed in your database

Setting the PHP SESSION user ID in my login function

Hi I was wondering if someone could please help me with my login function. Currently it will check to see if the username and password match an entry in the members table and if it does then sets the session variable authorised to true.
What Id like help with is when the session variable authorised has been set, I want to also set a user ID session variable, and by user ID I mean the numeric value - not the username which is in a column of the members table named memberID.
<?php
function login($user, $pass){
//strip all tags from varible
$user = strip_tags(mysql_real_escape_string($user));
$pass = strip_tags(mysql_real_escape_string($pass));
$pass = md5($pass);
// check if the username and password combination exist in database
$sql = "SELECT * FROM members WHERE username = '$user' AND password = '$pass'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
if (mysql_num_rows($result) == 1) {
// the username and password match,
// set the session
$_SESSION['authorized'] = true;
// direct to admin
header('Location: '.DIRADMIN);
exit();
} else {
// define an error message
$_SESSION['error'] = 'Sorry, wrong username or password';
}
}
?>
Please note, I am aware that md5() isn't the best method for password encryption and mysql_real_escape_string() and mysql_num_rows() are deprecated as of PHP 5.5.
Supposing that the column name in your DB is userId, all you have to do is add
$_SESSION['userId'] = $result['userId'];
under the line where you set the session.
So, it will look like
if (mysql_num_rows($result) == 1) {
// the username and password match,
// set the session
$_SESSION['authorized'] = true;
//set User Id
$_SESSION['userId'] = $result['userId'];
// direct to admin
header('Location: '.DIRADMIN);
exit();
}

limiting login attempts of user

i need help for limiting login attempt of the user. this is my code.
$login = login($username, $password);
if($login === false) {
if(isset($_COOKIE['login'])){
if($_COOKIE['login'] < 3){
$attempts = $_COOKIE['login'] + 1;
setcookie('login', $attempts, time()+60*10); //set the cookie for 10 minutes with the number of attempts stored
$errors[] = 'That username/password combination is incorrect!';
} else{
echo 'You are banned for 10 minutes. Try again later';
}
} else {
setcookie('login', 1, time()+60*10); //set the cookie for 10 minutes with the initial value of 1
}
} else {
$_SESSION['user_id'] = $login;
header('Location: ../../home.php');
exit();
}
it looks right for me but it just wont work. the user could still access his/her account even after attempting 3 login.
Use an SQL database, im currently working on a snippet of code, give me about an hour and ill throw an exampl up for you
PHP:
<?php
$host = "";//Host name
$username = "";//MYSQL username
$password = "";//MYSQL password
$db_name = "";//Database name
$tbl_name = "";//Name of login table
$bl_name2 = "";//Name of table to store IP if attempt is incorrect
//connect to server and select database
try{
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.'',$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}
catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();}
//get users ip next, as this is for a log in, this example will show for username and pass also
$userIP = $_SERVER['REMOTE_ADDR'];
$userPassword = $_POST['passwordfromform'];
$userUsername = $_POST['usernamefromform']
if(empty($userUsername) && empty($userPassword)){
die("You must enter a username and password");
}
//check for log in excess
$checkSql="
SELECT * FROM ".$tbl_name2."
WHERE PostersIP = '".$userIP."'
";
$stmt = $db->query($checkSql);
$row_count = $stmt->rowCount();
if($rowcount >= 7){//change this number to reflect the nuber of login chances
die("You have tried to log in too many times");
}
//check to log in
$insertSql = "
SELECT * FROM ".$tbl_name."
WHERE USERNAME = '".$userUsername."'
AND PASSWORD = '".$userPassword."'";
//execute check query
$result = $conn->query($insertSql);
if($result != false){
echo "Username and Password were correct!";//link to correct page
}
else{
$incorrectSql="
INSERT INTO ".$tbl_name2."
(PostersIP) VALUES
('".$userIP."')";
$result2 = $conn->query($incorrectSql);
if($result2 != false){
die("You entered an invalid username or password, your attempt has been stored.");
}
die("Error inserting data");
}
?>
I did not test this live, so there may be a few flaws, however i commented it pretty well for ya. you do need a second table to store user submission ips. this is a VERY messy way to do this. Im very sure there are better ways to do it, but theres my 10 minute solution :)
Use a database and I would suggest using IP address. check out this definitive way to get user ip address php
Capture the username, password and timestamp, record these to the table along whether failed or success. Set your parameters of when you want to ban them.
Add a check to you login script to check the IP address and only allow them to enter the details if that IP address hasn't been used for 3 failed attempts.
Obviously, you may need a new table for the banned IP address and the time when they are allowed to re-enter details.
I would just make another table that has cols: Username, Timestamp, Attempts.
This would check the username for attempts within 10 min of the timestamp (set on the first attempt).
If ( attempts > max attempts then attempt login )
{ "Sorry to many attempts"
else { Check login
if failed { Attempts++ } else (login success) { set attempts = 0 }
(reset attempts counter)}
}

Categories