How to make a new session with customer id? PHP/Mysqli - php

I have a login page which generates $_SESSION['username'] = $username.
I want to create new session $_SESSION['id'] which stores customer's id not username and pass it to another page.
I'm still learning so please make your answer understandable. Thanks
here's my login code
<?php
require('dbConfig.php');
session_start();
if(!empty($_SESSION["username"])){
header("LOCATION:index.php");
}
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($db,$username); //escapes special
characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($db,$password);
$query = "SELECT * FROM `members` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($db,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: index.php");
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>

Make sure session_start() is present is every page and add this in the session creation section of your code:
$_SESSION['id'] = $result['id'];
under
$_SESSION['username'] = $username;
I am asuming your "id" is called "id" in your table
You can use
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
To check whats in your session

First of all: try to use mysqli_prepare to query user, by passing variable directly into SQL code, you open your system to SQL Injection.
$query = "SELECT * FROM `members` WHERE username=? and password=?"
$password = md5($password);
$statement = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($statement, 'ss', $username, $password); //bind variables before execute sql command to prevent SQL injection.
mysqli_stmt_execute($statement);
$result = mysqli_stmt_get_result($statement);
$rows = mysqli_stmt_affected_rows($statement);
if($rows==1){
$user = mysqli_fetch_array($result, MYSQLI_ASSOC)
$_SESSION['username'] = $username;
$_SESSION['id'] = $user['id'];
header("Location: index.php");
}
Also, you must include session_start(); inside index.php in order to read SESSION variable on index.php page.

Related

login system not working using php and mysql

so im trying to get my login working which is using php and mysql. i dont no what to replace (mysqli_fetch_array) because before i was using md5 password and changed it to password hash. what i want the code to basically do is when the users correct email and password is inputted the page is redirected to (user-page.php) where the user info will be displayed. im only having problems with the login as the register is working with password hash
<?php
session_start();
require_once "connection.php";
if(isset($_SESSION['username'])!="") {
header("Location: user-page.php");
}
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$email_error = "Please Enter Valid Email ID";
}
$query = "SELECT `password` FROM `users` WHERE `email` = ?";
if(!empty($query)){
if ($row = mysqli_fetch_array($query)) {
$_SESSION['user_id'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SESSION['full_name'] = $row['full_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['gender'] = $row['gender'];
$_SESSION['medical_condition'] = $row['medical_condition'];
header("Location: user-page.php");
}
}else {
}
}
?>
the below code works by checking if the email exits and if the password is correct but only displays if the password is correct or incorrect. is there a way to redirect the user like the code above?
<?php
session_start();
require_once "connection.php";
if(isset($_SESSION['username'])!="") {
header("Location: user-page.php");
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$email_error = "Please Enter Valid Email ID";
}
$query = "SELECT `password` FROM `users` WHERE `email` = ?";
$params = array($_POST['email']);
$results = dataQuery($query, $params);
$hash = $results[0]['password']; // first and only row if username exists;
echo password_verify($_POST['password'], $hash) ? 'password correct' : 'passwword incorrect';
}
?>
register.php
<?php
require('connection.php');
if (isset($_POST['username'])){
$username = $_POST['username'];
$full_name = $_POST['full_name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$medical_condition = $_POST['medical_condition'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// insert values into the database.
$query = 'INSERT INTO `users` (`username`, `full_name`, `gender`,`email`,`medical_condition`, `password`) VALUES (?,?,?,?,?,?)';
$params = array($username, $full_name, $gender, $email, $medical_condition, $password);
$result = dataQuery($query, $params);
$_SESSION['username'] = $username;
$_SESSION['full_name'] = $full_name;
$_SESSION['email'] = $email;
$_SESSION['gender'] = $gender;
$_SESSION['medical_condition'] = $medical_condition;
if($result){
header("Location: user-page.php");
}
}else{
?>
When login in, after you check if password is valid, you need to fill your Session the same way you would after registering.
It differs from the registering, Instead of receiving all the information via the $_POST attribute, you need to get the information from the database and fill the $_SESSION.
So you would need to select more information from the query
$query = "SELECT * FROM `users` WHERE `email` = ?";
$params = array($_POST['email']);
$results = dataQuery($query, $params);
$hash = $results[0]['password']; // first and only row if username exists;
if ( password_verify($_POST['password'], $hash) )
{
$_SESSION['username'] = $results[0]['username'];
$_SESSION['full_name'] = $results[0]['full_name'];
$_SESSION['email'] = $results[0]['email'];
$_SESSION['gender'] = $results[0]['gender'];
$_SESSION['medical_condition'] = $results[0]['medical_condition'];
header("Location: user-page.php");
}
From my understanding of your question, you're trying to do a redirect with header("Location: user-page.php"); after doing password_verify($_POST['password'], $hash) and storing your user information in $_SESSION.
There is a single issue when using header() function as stated in the documentation :
https://www.php.net/manual/en/function.header.php
Note:
Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.
So you have to actually add the Session ID to the url manually for your session to persist to your next page.
It would look like this:
//https://www.php.net/manual/en/session.idpassing.php
//https://www.php.net/manual/en/function.session-id
//
//EDIT:
//307 Temporary Redirect
//Added slash "/" in front of php page. Better browser recognition.
header("Location: /user-page.php?".htmlspecialchars(SID),TRUE, 307);
//Use exit function to terminate program and make sure it does not perform any other tasks.
exit();

Session is not kept/destroyed when i navigate to other pages

Good day.SO i am having an issue in that, when i create a session via a login and a user is authenticated, once i leave that page to say a different page, i am not whether the session is destroyed or not created in the first place, i require this page to hold the session so i can be able to query the users email from it, and use it to query the database to determine the username.
This is my submit.php, called once the user clicks login on the page.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =$_POST['password'];
$sql = "SELECT * FROM `USERS` WHERE EMAIL='$email' AND ENCRYPTEDPWD='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['email'] = $email;
header("Location: Landing page.php");
exit();
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
?>
it redirects to the next page, the landing page.
This page should check email from the session, and then display a username.
<?php
session_start();
$_SESSION['email'] = $email;
$sql = "SELECT * FROM users WHERE EMAIL='$email';";
$result = mysqli_query($connection,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row['username'];
}
}
else{
echo "No User.";
}
?>
Please help.
You have an issue with the landing page in below line:-
$_SESSION['email'] = $email;// here you are assigning to SESSION
It needs to be:-
$email = $_SESSION['email'];//assign value from SESSION to variable
So code needs to be like this:-
$email = $_SESSION['email'];
$sql = "SELECT * FROM users WHERE EMAIL='$email'";
Note:- Your code is wide-open for SQL INJECTION. Try to use prepared statements to prevent it.
mysqli::prepare
In your landing page, invert the line after session_start(): You are assigning an empty variable to overwrite your already saved session variable
$email = $_SESSION['email'];
If your query causes you problems after that, try concatenating $email
$sql = "SELECT * FROM users WHERE EMAIL='".$email."';";

PHP pages restricted access by access level

In MySQL table I have:
ID
username
password
level
level "admin" = access to all pages
level "user" = access only to certain pages
In auth.php page (which is included in every page).
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit();
}
In login page I have:
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($conn, $username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn, $password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='" . md5($password) . "'";
$result = mysqli_query($conn, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if ($rows == 1) {
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
} else {
header("Location: login.php"); // Redirect user to index.php;
}
};
How should I make two sessions, session for "admin" and session for "user", so every page would have different access level?
Try this!
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
if ($result = $mysqli->query($con,$query)) {
while ($row = $result->fetch_assoc()) {
$_SESSION['username'] = $row["username"];
$_SESSION['level'] = $row["level"]);
}
$result->free();
}
Aftert that when a page requires a certain level just verify if the level is right.

Session Variables are lost after redirecting using header()

I have got index.php file that takes username and password from users, then it redirects to process_login.php that compares these credentials with SQL database to authorize the users. Now if the user is authorized, I want to get all the data about this user and want to use in other PHP files. I am using sessions to do so, but somehow they are not working.
I know they are so many similar questions, but none of them worked.
Here is my process_login.php code
<?php
session_start();
require_once('connectdatabase.php');
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
echo $count = mysqli_num_rows($result);
if($count == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}
else {
header('Location: ../../src/index.php');
}
}
?>
Now I want those variables on welcome.php file.
And this is my welcome.php code
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
It's because you are using $fist_name rather than $first_name. And edit your echo part
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
To
<?php
session_start();
$first_name = $_SESSION['first_name'];
echo $first_name;
?>
I wanted to comment but I can't so here is my suggestion for you.
When something like your issue happens to me I tend to echo the $_SESSION all of them to see if they're actually set or not.
Below is a small PHP script which does the same but I'm using PDO as the DB API.
if (isset($_REQUEST["pWord"])){
$inmPword = md5($_REQUEST["pWord"]);
$loginData = "SELECT * FROM userlogin WHERE pWord = :pWord";
$loginDataQuery = $dbConnect -> prepare($loginData);
$loginDataQuery -> bindParam(':pWord', $inmPword);
$loginDataQuery -> execute();
if ($row = $loginDataQuery -> fetch(PDO::FETCH_ASSOC)){
//Time to set the session
$_SESSION["uId"] = $row["uId"];
$_SESSION["uRole"] = $row["uRole"];
$_SESSION["fName"] = $row["fName"];
$_SESSION["lName"] = $row["lName"];
echo "3";
}else{
echo "4";
}
}
I think it's better not do the row count and echo it. Something like this might help.
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
if($row = mysqli_fetch_assoc($result)) {
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}

Can't receive mysqli record with password verify

I just started working with php and I'm not really good at it.I need to verify my user's password and username after they passed that I want to start an session with that users user_id. But everytime I try to echo the user_id I just get nothing back. hope someone can help me with this. is my code:
<?php
require_once "config.php";
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
if (strlen($username) > 0 && strlen($hash) > 0){
$query = "SELECT user_id FROM keep_user WHERE username = '$username' AND password = '$hash'";
$result = mysqli_query($conn , $query);
if($conn->query($query) == TRUE){
if(password_verify($password, $hash)){
session_start();
$_SESSION['user_id'] = $user_id;
echo $user_id;
echo "succes";
}else{
echo "error-1".$conn->error;
}
}else{
echo "error-2".$conn->error;
exit;
}
}else{
echo "error".$conn->error;
exit;
}
?>
It does echo success so I am guessing that part is good but why can't retrieve user_id?
Problem is not with password_verify function . Problem is with mysqli_query because you execute your query two times
$result = mysqli_query($conn , $query);// first time
if($conn->query($query) == TRUE){// second time
Just comment or remove $result = mysqli_query($conn , $query);// first time
To get user id form query you need to fetch it as
if ($result = $conn->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc() ;
$user_id=$row["user_id"];
$_SESSION['user_id'] = $user_id;
}
And session_start(); at the top of your page.
You script is open for sql injection Read How can I prevent SQL injection in PHP? to prevent it

Categories