PHP UserName and Password Validation Check - php

I'm creating a login page where the user name and password are entered and then checked against the database to see if they match (I have posted on this previously but my code was completely incorrect so I had to start over) Upon clicking the submit button the user should be directed to the homepage (index.php) if the two values match up or an error message should appear stating "Invalid login. Please try again." Very simple basic stuff. Yet, I cannot get any variation to work.
Here is my code without the validation check. I believe this code is right but, if not, could someone please explain as to why. I am not asking anyone to write any code, just explain why it is not working properly.
<?php
function Password($UserName)
{
//database login
$dsn = 'mysql:host=XXX;dbname=XXX';
$username='*****';
$password='*****';
//variable for errors
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
//try to run code
try {
//object to open database
$db = new PDO($dsn,$username,$password, $options);
//check username against password
$SQL = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME");
$SQL->bindValue(':USER_NAME', $UserName);
$SQL->execute();
$username = $SQL->fetch();
if($username === false)
{
$Password = null;
}
else
{
$Password = $username['USER_PASSWORD'];
}
return $Password;
$SQL->closeCursor();
$db = null;
} catch(PDOException $e){
$error_message = $e->getMessage();
echo("<p>Database Error: $error_message</p>");
exit();
}
?>
Now the validation code. I've googled this and found several hundred ways to do so but this method most closely matches my coding style. It is incomplete and I would like some help as to how to finish it properly and then where to place it within the code above. My assumption is right after this comment: "//check username against password". Now I've seen this version twice and in one version the check is for txtUserName and the other is just username. I believe there should be else statements after each if statement to direct them to the index.php page. Also, the third if statement is the check to see if the password matches the username. No variation of this did I understand. They were far too complex.
function Login()
{
if(empty($_POST['txtUserName']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['txtPassword']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['txtUserName']);
$password = trim($_POST['txtPassword']);
if(!$this->($username,$password))
{
return false;
}
}
I know I am asking a lot here. But I am very new to PHP and am really trying hard to learn it. And there is way too much info out there and most of it is not for beginners. Any, and all, help would be greatly appreciated.

To begin with, let's assume that we have a PDO connection, just like you do already, for example with this function:
You can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(Exception $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
So that you can have a database connection like this:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
$db = connectToDataBase($host, $databaseName, $user, $pass);
So far we have the same stuff as you.
Now, I assume that we're on a PHP page where the user submitted his username and password, to begin with: check if we really received the username and the password, with the ternary oprator:
// receive parameters to log in with.
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
Now you can validate if those inputs were actually posted:
// Check if all required parameters are set and make sure
// that a user is not logged in already
if(isset($_SESSION['loggedIn']))
{
// You don't want an already logged in user to try to log in.
$alrLogged = "You're already logged in.";
$_SESSION['warningMessage'] = $alrLogged;
header("Location: ../index.php");
}
else if($userName && $password)
{
// Verify an user by the email address and password
// submitted to this page
verifyUser($userName, $password, $db);
}
else if($userName && (!($password)))
{
$noPass = "You didn't fill out your password.";
$_SESSION['warningMessage'] = $noPass;
header("Location: ../index.php");
}
else if((!$userName) && $password)
{
$noUserName = "You didn't fill out your user name.";
$_SESSION['warningMessage'] = $noUserName;
header("Location: ../index.php");
}
else if((!$userName) && (!($password)))
{
$neither = "You didn't fill out your user name nor did you fill out your password.";
$_SESSION['warningMessage'] = $neither;
header("Location: ../index.php");
}
else
{
$unknownError = "An unknown error occurred.". NL. "Try again or <a href='../sites/contact.php' title='Contact us' target='_blank'>contact us</a>.";
$_SESSION['warningMessage'] = $unknownError;
header("Location: ../index.php");
}
Now, let's assume that everything went well and you already have a database connection stored in the variable $db, then you can work with the function
verifyUser($userName, $password, $db);
Like already mentioned in the first else if statement:
// Usage: verifyUser($userName, $password, $db);
// Pre: $db has already been defined and is a reference
// to a PDO connection.
// $userName is of type string.
// $password is of type string.
// Post: $user exists and has been granted a session that declares
// the fact that he is logged in.
function verifyUser($userName, $password, $db)
{
$userExists = userExists($userName, $db); // Check if user exists with that username.
if(!($user))
{
// User not found.
// Create warning message.
$notFound= "User not found.";
$_SESSION['warningMessage'] = $notFound;
header("Location: ../index.php");
}
else
{
// The user exists, here you can use your smart function which receives
// the hash of the password of the user:
$passwordHash = Password($UserName);
// If you have PHPass, an awesome hashing library for PHP
// http://www.openwall.com/phpass/
// Then you can do this:
$passwordMatch = PHPhassMatch($passwordHash , $password);
// Or you can just create a basic functions which does the same;
// Receive 1 parameter which is a hashed password, one which is not hashed,
// so you hash the second one and check if the hashes match.
if($passwordMatch)
{
// The user exists and he entered the correct password.
$_SESSION['isLoggedIn'] = true;
header("Location: ../index.php");
// Whatever more you want to do.
}
else
{
// Password incorrect.
// Create warning message.
$wrongPass = "Username or password incorrect."; // Don't give to much info.
$_SESSION['warningMessage'] = $wrongPass;
header("Location: ../index.php");
}
}
}
And the function userExists($userName, $db) can be like:
function userExists($userName, $db)
{
$stmt = $db->prepare("SELECT * FROM users WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME "=>$userName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
// User exists.
return true;
}
// User doesn't exist.
return false;
}
Where the function Password is like:
function Password($UserName)
{
$stmt = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME"=>UserName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['USER_PASSWORD'];
}
// No result.
return false;
}
Again, make sure you're not matching plain text passwords, or basic shai1, md5 encryptiones etc. I really recommend that you take a look at PHPass.
I hope I'm making myself clear.

Related

Am I using any outdated logic in my php login script?

So here is the deal, I have been following tutorials all day trying to resolve this issue I am having.
So far my webpage shows "Username invalid" , but I have confirmed in the inspector in chrome that it is infact passing the correct username and password to my login script (below) am I doing anything wrong?!
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'db_ip';
$DATABASE_USER = 'db_user';
$DATABASE_PASS = 'db_pass';
$DATABASE_NAME = 'db_name';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
exit('Please fill both the username and password fields!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare("SELECT id, password FROM `accounts` WHERE username = '$username'")) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if ($_POST['password'] === $password) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
}
?>
I was able to resolve my issue with the following:
where I was defining $stmt I was using $username when it had not been defined yet, I changed this line
$con->prepare("SELECT id, password FROM `accounts` WHERE username = '$username'"))
to
$con->prepare('SELECT id, password FROM `accounts` WHERE username = ?'))
and added this above my execute statement:
$stmt->bind_result($id, $password);

Kind Assistance with Pulling Currently Logged User ID and First Name from Database

I am building a study planner that features just a single welcome area, after logging in. I am currently trying to obtain the user ID of the currently logged in user for use in an SQL update query in this welcome area, as well as the user’s first name for use in the welcome message.
I have tried putting $_SESSION['user_id'] = userid; and $_SESSION['user_firstname'] = firstname; after $_SESSION['login_user'] = $username; ($_SESSION['login_user'] = $username; works fine by the way) but upon logging into the page, I get these errors: Notice: Use of undefined constant userid - assumed 'userid' in C:\wamp64\www\justread\session.php on line 11 and Notice: Use of undefined constant firstname - assumed 'firstname' in C:\wamp64\www\justread\session.php on line 12.
Now, I know the errors want me to do some sort of initialisation for ‘userid’ and ‘firstname’ first before using them to set up a session variable but I am not sure how to go about it, so I am wondering if someone could help me, please.
Thanking you in advance.
I can post more codes if required but the codes I believe are concerned are:
login.php:
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
// Storing Session
$user_check = $_SESSION['login_user'];
$_SESSION['user_id'] = userid;
$_SESSION['user_firstname'] = firstname;
// Test to see the content of the global session variable
print_r($_SESSION);
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysqli_query($mysqli, "SELECT username FROM logins WHERE username='$user_check'");
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
// Closing Connection
mysqli_close($mysqli);
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
In PHP, variable name starts with '$' sign. Also, in login.php, you have to fetch the data using mysqli_fetch_row or any similar function. Am assuming you are redirecting to session.php after logging in. In that case, you don't have to assign anything to the session variables. It will be there already. All you have to do is to access it.
login.php
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
$row = mysql_fetch_object($query);
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = $row->userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = $row->firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
if (!isset($_SESSION['user_id'])) {
// Closing Connection
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
print_r($_SESSION);
Also, move the connection part to a seperate file and include it in all scripts, so that when your credentials change, you don't have to change it in all the files.

MySQL Query is fine, doesn't give a value or an error

I am trying to find how to check if a variable called active is equal to 1. My attempt at the function is below:
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt, active
FROM members
WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt, $active);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
if (!$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')")) {
header("Location: ../error?err=Database error: login_attempts");
exit();
}
return false;
}
}
} else {
// No user exists.
return false;
}
} else {
// Could not create a prepared statement
header("Location: ../error?err=Database error: cannot prepare statement");
exit();
}
}
I assume that where I added active to the $mysqli->prepare statement is correct.
What I want to do is if the user got their password correct I would query the MySQL table to see if his account is active(1) or not active(0). If it is set to 0 it logs in with no error. However in my process_login.php file it logs the user in if it is (0) but with index.php?err=1
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header("Location: ../protected_page.php");
exit();
} else {
// Login failed
header('Location: ../index.php?error=1');
echo $active;
exit();
}
} else {
// The correct POST variables were not sent to this page.
header('Location: ../error.php?err=Could not process login');
exit();
}
When I try to echo the variable $active it returns nothing.
Any help is appreciated in advance.
Posting this as a community wiki; I don't want rep for it, nor should there be any made from it.
A: You did not follow that tutorial exactly as it was written.
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
since it is obvious that that is where that code comes from; I know it all too well.
You modified some parts of the code and left some out also.
Go back to the tutorial, and follow it " to a T ". You may also have to clear out your present hashes and start over.
Make sure that the table creation was done exactly as shown. If you failed to make the right columns and their proper lengths, then that will fail "silently" on you.
Consult the comments I left under the question also.

PHP Authentication works only local

I have a PHP login page that works perfectly locally, but when in server always come out with "Invalid Username or Password". I tried it in two different servers and the result was the same.
login.php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = "Username or Password is invalid";
}
else
{
// Define $username1 and $password1
$username1 = $_POST['username'];
$password1 = $_POST['password'];
include_once ('lib/db.php');
$connection = new mysqli($servername, $username, $password, $dbname);
$username1 = stripslashes($username1);
$password1 = stripslashes($password1);
$username1 = mysql_real_escape_string($username1);
$password1 = mysql_real_escape_string($password1);
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from login where PASSWORD='$password1' AND USERNAME='$username1'";
$result = $connection->query($query);
$rows = mysqli_num_rows($result);
if ($rows == 1)
{
$_SESSION['user']=$username1; // Initializing Session
$_SESSION['pppv'] = 10;
header("Location: logged-in.php"); // Redirecting To Other Page
}
else
{
$error = "Username or Password is invalid";
}
}
}
EDIT
Try printing the query after submission gives me this:
Local:
select * from login where PASSWORD='test' AND USERNAME='test'
Server:
select * from login where PASSWORD='' AND USERNAME=''
Use isset($_POST['username']) ||isset($_POST['password'])instead of empty($_POST['username']) || empty($_POST['password']).
Read this to know the difference between isset and empty.
There's no context, but check these things:
Does your database contain the same credentials as local?
Does your requested page return http status such as 200? If it's 404, there's something wrong with your path's. If it's 500, there's an internal error (right permissions set?)
Did you check your log files?
Did you clear your browser cookies and history?
Did you print the full query (including filled parameters) to the window and did you execute this query in your database management tool? And did you get result?

php user login not working anymore after I changed the way of error handling

I am trying to implement a user login service on my website, registered users fill in the login form and they are transferred to member.php page, in the past I was using try and catch block and throwing exceptions, and it was working fine:
member.php
<?php
require_once('repository_fns.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
try {
login($username, $password);
$_SESSION['valid_user'] = $username;
}
catch(Exception $e) {
do_html_header('Problem:');
echo 'You could not be logged in.
You must be logged in to view this page.';
do_html_url('login.php', 'Login');
do_html_footer();
exit;
}
}
$current_user=$_SESSION['valid_user'];
do_html_header_member();
do_page_content_member($current_user);
do_html_footer();
?>
the login function was like:
function login($username, $password) {
$conn = db_connect();
$result = $conn->query("select * from user
where username='".$username."'
and password = sha1('".$password."')");
if (!$result) {
throw new Exception('Wrong password, could not log you in.');
}
if ($result->num_rows>0) {
return true;
} else {
throw new Exception('Exception: could not log you in.');
}
Now I have removed those try and catch blocks, and member.php is like:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once('repository_fns.php');
session_start();
if (($_POST['username']) && ($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password){
$_SESSION['valid_user'] = $username;
}
else{
do_html_header_error_page();
do_error_message_cannot_login();
do_html_footer();
exit;
}
}
$current_user=$_SESSION['valid_user'];
do_html_header_member();
do_page_content_member($current_user);
do_html_footer();
?>
login function:
function login($username, $password) {
$conn = db_connect();
$result = $conn->query("select * from user
where username='".$username."'
and password = sha1('".$password."')");
if (!$result) {
return false;
}
if ($result->num_rows>0) {
return true;
} else {
return false;
}
}
I don't why it's not working anymore, member.php just gives me a blank page now, without any error messages. Please help! Thank you in advance.
I gave you the answer in comments, but let me expand then.
You should have an error log stating such like:
PHP Parse error: syntax error, unexpected '{' in /member.php on line 9
Line 9 is:
if(login($username, $password){
Unexpected "X" means something before it is wrong, did not complete, is not present. Because we hit something unexpected.
In this case you are missing a closing parenthesis - corrected code::
if(login($username, $password)){
SIDE NOTES - to help perhaps:
If you get a good IDE or code editor, it would highlight this for you.
I use Vim, and pasted your code and the issue showed up straight away.
Another hint, while coding conventions and standards are your choice, a space before the opening brace helps see the code before it more clearly.
e.g. your broken code with the space added is:
if(login($username, $password) {
You can see there is a missing ) more easily.

Categories