How do I use a $_SESSION['variable'] from one session in another? - php

I'm making a web app where the user logs in and is able to access the profile and take a quiz. I've got most of it working the only problem is, is that it seems to 'forget' which user is signed in. By this I mean I can't access any of the variables from when the user logs in session.
For example, I have a $_SESSION['username'] = $username; which returns unidentified variable when I try to use the variable $username in a different session or page. Also, I haven't terminated my login session.
Right now I'm trying to store the results of my quiz to a database along with the user's username but it only stores the score and not the username.
Below is my code.
authenticate.php file (This contains the variables regarding usernames)
<?php
session_start();
// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data 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.
die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $con->prepare('SELECT username, password FROM users WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the st_account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($username, $password);
$stmt->fetch();
// st_account exists, now we verify the password.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['username'] = $username;
include_once 'homepage.php';
// echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect username and/or password!';
}
} else {
echo 'Incorrect username and/or password!';
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
?>
final.php file
<php include "process.php"?>
lines 24 - 44
<main>
<div class="container">
<h2>You are Done!</h2>
<p>Congrats! You have completed the test</p>
<p>Final score: <?php echo $_SESSION['score']; ?></p>
<?php echo $score; ?>
Take Test Again
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$query = "INSERT INTO `results`(`username`,`score`) VALUES ($username, $score)";
mysqli_query($con, $query);
?>
<?php session_destroy(); ?>
</div>
I don't know if it's necessary to include process.php but I thought it might be helpful to show where the $score variable comes from.
process.php file (this isn't the whole file.)
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
//Check to see if score is set_error_handler
if (!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
}
$score = $_SESSION['score'];
}
?>
Sorry if I've made a really simple stupid error, don't hate me, I'm still pretty bad at coding.

Put your session_start(); at the very top of your code, for example, at the very top of your final.php file rather than in your process.php file.
E.g.;
<?php
session_start();
include 'database.php';
?>

A simple solution that you can try
session_start();
We have to add this on the top of php file, or else php throw exceptions like 'headers already sent' or 'can’t start the session' etc.

Related

Why my SESSION varis empty when I call another PHP file? [duplicate]

I've got a login system set up, and there are no problems with staying logged in. Both userid and username are stored as session variables (and stored in a table in the database), and I can access them for use within the html on the pages themselves just fine.
I have a form with several multiple choice questions. Any answers I put in the form are stored in the database correctly, no problems there. But when I try to put the username or id into the table, it doesn't work.
The username is displayed on survey.php (the page with the form on it) in the html, like so:
<h2><?php
echo $_SESSION['userName'];
?></h2>
Before I submit the form, the username is displayed correctly. After submitting the form, the same page reloads and the username is still displayed correctly. I'm not being logged out. $_SESSION['userName'] is not being reset and it's not empty.
The code below works perfectly as is, but if I replace
$locationMC = $_POST['locationMC'];
with
$locationMC = $_SESSION['userName']; # (the commented out line in the code below)
it redirects me to /survey.php?error=emptyfields, so $locationMC isn't being set when I try to use the session variable.
The users table and testingtable are in the same database. UserID is set as the primary key, but userName isn't indexed.
Something tells me I'm missing something super basic here -- I'm really new to this -- but after hours of searching on google, I can't figure out what the problem is. Thanks for any help!
<?php
if (isset($_POST['submit'])) {
require 'dbh.inc.php';
$locationMC = $_POST['locationMC'];
# $locationMC = $_SESSION['userName'];
$genderMC = $_POST['genderMC'];
$religionMC = $_POST['religionMC'];
if (empty($locationMC)) {
header("Location: ../survey.php?error=emptyfields");
exit();
}
else {
$sql = "INSERT INTO testingtable (locationMC, genderMC, religionMC) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../survey.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sss", $locationMC, $genderMC, $religionMC);
mysqli_stmt_execute($stmt);
header("Location: ../survey.php");
exit();
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../survey.php");
exit();
}
Below is dbh.inc.php. It's the same file that's used when signing up and logging in.
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "testingdb";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
you need to start request session to read its content
add this code in you top header
if(!isset($_SESSION)) session_start();

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.

PHP login got Too Many Redirect Loop error

Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.

Logging in not creating a session

I'm trying to log in to my site, I'm looking at the database and the username/password are correct. When logging in I should be greeted by ja message that says "Welcome Ryemck" as "Ryemck" is my username, but this could be replaced by any username that is logged in. Here's the code to show that:
<td>Welcome </td>
<td><i><?php echo $username ['username']; ?></i></td>
However, instead of that nice message I get "Notice: Undefined variable: username ", I assume this is because the username isn't being set as the variable as it should in this code.
$username=$_POST['username'];
I also have this code that SHOULD give me the error if no username/password are entered, but it doesn't, so this doesn't work. is "session_start();" not the correct session code?
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
EDIT
<?php
session_start(); // Starting Session
echo "hello";
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
echo "hello";
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db("game", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: header.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
Change it to:
<td><i><?php echo $username; ?></i></td>
$username is not an array , gli must write :
<td>Welcome </td>
<td><i><?php echo $username ; ?></i></td>
I am not sure if i am reading this right are you looking to start a new session at the top of the page and the store values in that session?.
if you place something like the following at the top of your page it will remember sessions variables
if(!isset($_SESSION)){session_start());
You would then assign to a session variable using
$_SESSION["userName"] = $_POST["userName"];
To tell if its be set to grant access to a admin console you could do something like
if(isset($_SESSION["userName"]) && $_SESSION["userName"] != '')
the above means that the variable has been set but you would probably wrap the session userName in a db function to check for valid logins.
The button I was clicking was set to "login" whereas the isset was set to "submit".
Simply changing the words solved it.

Categories