Creating one of two sessions php - php

Im trying to create two different sessions. One for the admin, the other for normal users. If SQL returns admin_role as 1 = admin. If admin_role as 0 = user.
I have session_start() in the beginning of the document via include('connection.php'). When I press submit on my login form nothing really happens as for now.
if(empty($_POST["username"]) || empty($_POST["password"])){
$error = "Fill in both fields!";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
// Check username and password from database
$sql = "SELECT admin_role FROM user WHERE user_name='$username' AND user_password='$password'";
$result = mysqli_query($db, $sql);
$admin_role = $row['admin_role'];
// If username and password exist in our database then create a session.
// Otherwise echo error.
if(mysqli_num_rows($result) == 1){
if($admin_role == 1){
$_SESSION['admin'];
header("location: logged-in.php");
}
if($admin_role == 0){
$_SESSION['username'];
header("location: logged-in.php");
}
} else {
$error = "Wrong credentials";
}
}

Related

password_verify for hashed password

I have admin page that will insert user id, password, role. The password will be hash after admin insert new user. It work well but when I try to login using the hash password, it will pop up "invalid user or password". Maybe because I put the password_verify coding in the wrong place. Can someone help me!!
Below is my coding
login.php
<?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 $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "","company");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection, "select * from login where password='$password' AND username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$pwdCheck = password_verify($password,$row['password']); $_SESSION['user']=array(
'username'=>$row['username'],
'password'=>$row['password'],
'role'=>$row['role']
);
$role=$_SESSION['user']['role'];
//Redirecting User Based on Role
switch($role){
case 'user':
if ($pwdCheck == true)
header("location: index.php"); // Redirecting To Other Page
break;
case 'admin':
if ($pwdCheck == true)
header("location: adminindex.php"); // Redirecting To Other Page
break;
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
crud_include.php (admin insert new user)
if (isset($_POST['save'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$role = $_POST['role'];
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_query($db, "INSERT INTO login (username, password,role) VALUES ('$username', '$hashedPwd','$role')");
$_SESSION['message'] = "Successfully saved!";
header('location: crud.php');
}
the database (the hash work well but i cannot login using this user
Change your select query : In a where case use only username
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$query = mysqli_query($connection, "select * from login WHERE username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
if (password_verify($password, $row['password'])) {
echo 'Password is valid!';
if($role=$_SESSION['user']['role'] == 'user'){
header("location: index.php");
}elseif($role=$_SESSION['user']['role'] == 'admin'){
header("location: adminindex.php");
}
} else {
$error = "Password is invalid";
}
}else{
$error = "Username is invalid";
}
?>
Hope it will help you.
Here the the link for the hash password verified

Verifying user login against hash stored in database

I know this one has been asked before but have not been able to find a solution on previous questions.
Secure hash and salt for PHP passwords
Password verifying against database using bcrypt
php password_verify not working with database
I'm attempting to hash the password when registering and then verify it when trying to login. The query is retrieving the password associated with the username however isn't being verified correctly.
The problem is the way I am trying to use password_verify but no matter what I'v tried the past few hours I haven't been able to get it working. If anyone could take a look and try spot what I'm doing wrong it would be a great help.
The DB column length is set to 255 and Varchar to allow the full hash entry.
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_array($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
So I know the hash being returned from the database is being set in the $stored_hash variable correctly as if I hard code the hash returned from it and compare it, login is correct. Could it be something altering the input somewhere?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
Function is_valid_entry($inputData,$validData)
{
$inputData_array = str_split($inputData);
$validData_array = str_split($validData);
$i = 0;
while ($i < sizeof($inputData_array))
{
if (!in_array($inputData_array[$i],$validData_array))
{
return false;
}
$i++;
}
return true;
}
//User defined global variables go here
$username = "";
$ID = "";
$errorMessage = "";
$valid_chars = "abcdefghijklmnopqrstuvwxyz
1234567890";
session_start(); //start a session
if (isset($_POST['submit'])) { //submit button has been clicked
$username = $_POST['username'];
$username = trim($username); //trim any white spaces in the input value
$username = lcfirst($username); //attempts to convert upper case to lower
$username = htmlspecialchars($username); //convert special chars to html rendering null
$username = strip_tags($username); //Strip tags from input string
$ID = $_POST['ID']; //read in the value the user has entered for the password and assign to $ID
$ID = htmlspecialchars($ID);
$ID = strip_tags($ID);
$ID = trim($ID);
if (!is_numeric($ID)) { //if $ID is not numeric redirect to login page
$errorMessage = "Invalid username or password.";
$_SESSION['error'] = $errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php');
} else if (!is_valid_entry($username,$valid_chars)) { //check that user name is a valid char
$errorMessage = "Invalid username or password";
$_SESSION['error'] = errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php'); //redirect the user to the login page
} else { //if user name & $id are both valid
//now check if they are in the database
$mySQL_Server = "127.0.0.1";
$db_userName = "root";
$db_password = "";
$database = "projectdatabase";
//connect to the database on the MySQL server & store the connection in $conn
$conn = mysqli_connect($mySQL_Server, $db_userName, $db_password, $database);
if (mysqli_connect_errno($conn))
{
print("Error connecting to MySQL database: " . mysqli_connect_error($conn));
} else
{
print("Connected to the MySQL database");
}
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_assoc($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "$ID, $stored_hash"; //test to ensure is reaching this statement
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
mysqli_close($conn);
}
}
?>

How to set user/admin accounts for a redirect after log in? PHP

My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
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 $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?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 $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.

How i connect my login.php like my register.php?

I have just connected my register.php to mysql database. and i try connect my login.php but i cant.
this is my connected register.php
$connect = mysqli_connect("mysql13.000webhost.com","a2955851_SW","********");
if(isset($_POST['submit']))
{
$username = mysqli_real_escape_string($connect, $_POST['username']);
$pass = mysqli_real_escape_string($connect, $_POST['pass']);
$pass1 = mysqli_real_escape_string($connect, $_POST['pass1']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
if($username && $pass && $pass1 && $email)
{
if($pass==$pass1)
{
mysqli_select_db($connect, "a2955851_SW");
$query = mysqli_query($connect, "INSERT INTO users VALUES('$username','$pass','$email');");
echo "You have been registered.";
}
else
{
echo "Password must match.";
}
}
else
{
echo "All fields are required.";
}
}
and this is login.php i tryed connect this but...
<?php
$connect = mysqli_connect("mysql13.000webhost.com","a2955851_SW","********");
session_start();
if(isset($_POST['login']))
{
$username = mysqli_real_escape_string($connect, $_POST['username']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
if($username && $password)
{
mysqli_select_db($connect, "a2955851_SW");
$login = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($log=mysqli_fetch_assoc($login))
{
$dbusername = $log['username'];
$dbpassword = $log['password'];
}
if($username==$dbusername && $password==$dbpassword)
{
$_SESSION['username'] = $dbusername;
$_SESSION['password'] = $dbpassword;
header("location:members.php");
}
else
{
header("location:index.php?notify=Incorrect Username or Password.");
}
}
else
{
header("location:index.php?notify=ALL field are required.");
}
}
?>
i tried connect login.php similarly I do not know
You have mixed mysql & mysqli. Use only one. Change
$login = mysql_query("SELECT * FROM users WHERE username = '$username'");
to
$login = mysqli_query($connect, "SELECT * FROM users WHERE username = '$username'");
I am not really sure but try changing the following line:
$password = mysqli_real_escape_string($connect, $_POST['password']);
to
$password = $_POST['password'];
this is because at the later part of your script, you will be checking
if($username==$dbusername && $password==$dbpassword)
and if $password is escaped, $dbpassword will not be and the same password might result in a false comparison.
Lets say the actual password is 12"3, $password will be 12\"3 and $dbpassword will be 12"3 if $password is escaped.
The best way is to make a connection file and include in all php file you want to connect to database. So you don't need to check in every page and run your query before just below connection string to make sure its working
$query = mysqli_query($connect, "INSERT INTO users VALUES('$username','$pass','$email');");
echo "You have been registered.";
}

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories