Session variables not working? (PHP) - php

I am having an issue with 2 files: login_config.php and profile.php.
login_config.php consists of a log in system, which sets $_SESSION['key'] true upon the completion of several forms of authentication.
profile.php is the page the user is redirected to after success.
I want data on profile.php to only be accessible with $_SESSION['key'] set (upon successful login).
My question: What is incorrect with my code? Furthermore, why am I presented with the error upon login submission that is only supposed to return if $_SESSION['key'] is false/not set, as opposed to the targeted profile.php page?
CODE: (login_config.php)
<?php
// POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
// PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
if(!$veri_password === true){$errors[] = '-Account does not exist ';}
// CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$user_pass' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
// ERRS ARRAY ESTABLISHED
$errors = array();
// FURTHER VERIFYING
if( empty($password) || empty($email) )
{
$errors[] = 'Please do not leave fields empty';
}
elseif( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
$_SESSION['key'] === true;
while($row = mysql_fetch_array($entered_user)){
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
CODE: (profile.php)
<?php
session_start();
if($_SESSION['key'] !== true){
die ("please <a href='login.php'>log in</a> to view this page");
}
?>
<html>
<head>
<title>Profile</title>
<link href='css/main.css' rel='stylesheet' />
</head>
<body>
<div id='container'>
<?php require 'include/header.php'; ?>
<?= 'NJM ID # ==>'.$_SESSION['id'].'<br />'.'Username ==>'.$_SESSION['user'].'<br/>'.'Password ==>'.$_SESSION['pass'].'<br/>'.'<br />' ?>
<a href='logout.php'>Log out!</a>
<br />
-OR-
<br />
<p>Try our beta mode<a href='forum.php'> forum</a></p>
<?php require 'include/footer.php'; ?>
</div>
</body>
</html>
Note: I am aware I am vulnerable to SQL attacks at the current state of code, I will be fixing this later, also I am stuck with the deprecated version of MySQL.

In profile.php you have to call session_start(); before using $_SESSION. session_start() doesn't just start a new session, but will also continue an existing session (it will 'start' the session handling functionality, if you will). Without calling it, you cannot use $_SESSION.

1st: I would use termary operators for checking the existence of the values I need, for avoiding the "undefined index 'login_username'" error. Like this:
$username = isset($_POST['login_username']) ? $_POST['login_username'] : '';
$password = isset($_POST['login_password']) ? $_POST['login_password']) : '';
$email = isset($_POST['login_email']) ? $_POST['login_email'] : '';
2nd: I would use PDO for connecting with the MySQL server, for security reasons, and not only.
session_start();
if (isset($submit)){
// select all data from db for the current user
$st = $db->prepare('SELECT * FROM users WHERE email=?');
$st->execute([$email]);
//$rows = count_rows_here
if($rows == 1){
$row = $stmt->fetch();
if(password_verify($password, $row['pass'])){
$_SESSION['key'] = true; // notice the '=', and not '==='
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $row['email'];
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $row['password'];
header('Location: profile.php');
} else {
echo 'Error!';
}
}
}

I have fixed this by assigning the $_SESSION['key'] a variable with a value.
$_SESSION['key'] = $check = 'check';
Then to test this in profile.php, I have entered the following code:
if(isset(!$_SESSION['key'])){die ('example')}

I would try first to remove the exit() call after you have headered to the next PHP page. It isn't necessary as you have no code below it and it might be affecting the session (I don't think so though)
If this doesn't work (probably wont) add to profile.php after you have started the session var_dump($_SESSION) and have a look/post its contents.

Related

session value lost after redirection in php

PHP session value lost after header redirection in php
Our code
Login.php
<?php
session_start();
include('./includes/variables.php');
include_once('includes/custom-functions.php');
$fn = new custom_functions;
if (isset($_POST['btnLogin'])) {
// get username and password
$username = $db->escapeString($fn->xss_clean($_POST['username']));
$password = $db->escapeString($fn->xss_clean($_POST['password']));
// set time for session timeout
$currentTime = time() + 25200;
$expired = 3600;
// create array variable to handle error
$error = array();
// check whether $username is empty or not
if (empty($username)) {
$error['username'] = "*Username should be filled.";
}
// check whether $password is empty or not
if (empty($password)) {
$error['password'] = "*Password should be filled.";
}
// if username and password is not empty, check in database
if (!empty($username) && !empty($password)) {
// change username to lowercase
$username = strtolower($username);
//encript password to sha256
//$password = md5($password);
// get data from user table
$sql_query = "SELECT * FROM admin WHERE username = '" . $username . "' AND password = '" . $password . "'";
$db->sql($sql_query);
/* store result */
$res = $db->getResult();
// print_r($res);
// die();
$num = $db->numRows($res);
// Close statement object
if ($num == 1) {
$_SESSION['id'] = $res[0]['id'];
$_SESSION['role'] = $res[0]['role'];
$_SESSION['user'] = $username;
$_SESSION['timeout'] = $currentTime + $expired;
//print_r($_SESSION);
//die();
header("location: home.php");
exit();
} else {
$error['failed'] = "<span class='label label-danger'>Invalid Username or Password!</span>";
}
}
}
?>
Home.php
<?php session_start();
print_r($_SESSION);
?>
Output :
array()
We tried the following method
Made sure session_start(); is called before any sessions are
being called
After the header redirect, end the current script using exit();
Made sure cookies are enabled in the browser we were using to test
it on.
Made sure didn't delete or empty the session
Made sure file extension is .php
You have to include you file in which you have initialized session
For example
first file named phpcodeonly.php:
session_start() //put it in start
if(login success){
$_SESSION['email']= $email
}
your other file.php:
include 'phpcodeonly.php'; //on top
<h1> Welcome <?php echo $_SESSION['email']?> </h1>

PHP cant get session to store UserID after declaring it on login form

I am a PHP novice so please forgive my lack of knowledge.
So I have a login form that is run using the following (it all works fine)
<?php include 'connectionDetails.php'; ?>
<?php session_start(); ?>
<?php
if (isset($_POST['username']) and isset($_POST['password']))
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$sql = "SELECT UserID, Username, Password FROM Users WHERE Username = ? AND Password = ?";
$user = $username;
$pass = $password;
$userid = $sql['UserID'];
$stmt = sqlsrv_prepare($conn, $sql, array(&$user, &$pass));
if( !$stmt )
{
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
if (sqlsrv_has_rows($stmt) > 0)
{
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $user;
$_SESSION["userid"] = $userid;
header('location: index.php');
}
else
{
echo "Sorry wrong details!";
}
}
?>
Once the user is logged in all is fine and I can use those session variables to display the name of the user that is logged in.
Now I am creating a separate script that will insert into the database and more specifically against the user that is logged in at the time.
This is a separate script that is run when I click submit on a button:
<?php
session_start();
if ( isset($_SESSION['username']) ){
echo $_SESSION['username'] . $_SESSION['UserID'];
}
?>
I feel like I might possibly have declared it wrong or over-complicated it, I would appreciate any guidance.
EDIT: This just echoes the letter "S" for some reason.

store $username and $file variables in the $_SESSION after login

From index.php I get the values of the username and password fileds with $_POST
index.php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = mysql_real_escape_string(strtolower($_POST['username']));
$password = mysql_real_escape_string($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
checkUser($_SESSION['username'], $_SESSION['password']);
}
Then I store these $username and $password variables inside the $_SESSION and call a function checkUser($_SESSION['username'], $_SESSION['password'])); which sends two parameters. The checkUser() function executes inside lib.php
lib.php
session_start();
function checkUser($username, $password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
$logic = true;
echo "HI,".$username;
?>
<a href='logout.php'>Log Out</a>
<?php
$file = $row['file'];
echo "<img src='images/users/".$file."' >";
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
}
This part is for showing the name of the user and the image according to it.
logout.php works
logout.php
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["file"]);
header("Location: index.php");
session_destroy();
The problem is when I navigate from one page to another, the $_SESSION variable becomes empty. Something is wrong with session. Please help me.
in the php pages you need to access session variable add session_start() after the starting <?php code

How to redirect to different page after form is submitted using header()?

I've looked at lots of answers to redirect to a different page after submitting a form, but haven't been able to get it to work thus far, probably because I have no idea where to actually put the code. Can anyone help? The rest of this code is working fine, i just need to know where to place header():
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connects to database, checks username & password against database to see is user exists
if($username && $password)
{
include ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows !==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//if username and password are correct
if($username==$dbusername&&md5($password)==$dbpassword)
{
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
}
//if password is incorrect
else
echo "Your password is incorrect.";
}
//if username is incorrect
else
die("Username does not exist.");
}
//if no information is submitted
else
die("Please enter your login details.");
//prevents errors from displaying on page
error_reporting(0);
?>
I also need to know where it goes for this page:
<?php
//Check if register button was pressed
$button = $_POST['button'];
//if button was pressed,
if ($button)
{
//get data from form,
$username = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
}
//check if all information has been entered,
if ($username && $password && $retype_password && $first_name && $last_name)
{
//check if password and retype_password are the same
if($password==$retype_password)
{
//check if username already exists
include("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows == 0)
{
//encrypt password
$password = md5($password);
//sends data from form to database - creates new user
$register = mysql_query("INSERT INTO users VALUES ('', '$username', '$password', '$first_name', '$last_name')");
echo "You are now registered. <a href='main.php'>Continue to site.</a>";
}
else
echo "Username is unavailable.";
}
else
echo "Password did not match.";
}
//prevents errors from displaying on page
error_reporting(0);
?>
Thanks in advance!
if($username==$dbusername&&md5($password)==$dbpassword)
{
$_SESSION['username'] = $username;
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
You should put it once the job is done : that is after
//echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Don't forget the "exit" or what follow will be executed.
That said, you cannot echo something before a doing redirection, that's logical because the echo can't be seen.
So, either you do not echo :
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Or you do a HTML (or javascript) redirection, with a 5 seconds delay:
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
exit;
In which case you have to put it in the < head > section, to do the HTML redirection:
<meta http-equiv="refresh" content="0; url=http://example.com/main.php" />
Also
error_reporting(0);
Should be put at the beginning of the page, unless you want errors for previous lines to be shown.
BUT : error_reporting(0); should NEVER be used on a development site (and always on a production site).
You should turn on display_errors('on') and error_reporting(E_ALL) to see errors - errors are very useful for a developer.

PHP Header function and $_SESSION variables not working

I am doing a project on two different servers, my code works perfectly on one server and refuses to work on the other.
The purpose of the code is for a user to login on the login.php page, and be redirected to the dashboard.php page, if their login credentials are correct. The header.php file simply contains information for the nav bar for different people logging in.
Please let me know where the error could be.
I'm not sure whether these are two distinct problems but both the Header redirect is not working, and neither are the session variables being stored. I made sure I didn't echo out anything before the header redirect.
Login.php
<?php include('header.php');?>
<?php
session_start();
$dbusername = $_SESSION['username'];
$dbfName = $_SESSION['fName'];
$dblName = $_SESSION['lName'];
$sessiontype = $_SESSION['type'];
if($dbusername && $dbfName && $dblName && $sessiontype){
header('Location: ./dashboard.php');
}
if(isset($_POST['login_button'])){
session_start();
$getuser = $_POST['username'];
$getpass = $_POST['password'];
$getpassmd5 = md5(md5($getpass));
if($getuser && $getpass){
require('connect.php');
$query1 = "SELECT * FROM students WHERE StudentNum='$getuser'";
$exequery1 = mysql_query($query1);
if(mysql_num_rows($exequery1) > 0){
while ($row = mysql_fetch_assoc($exequery1)){
$dbusername = $row['StudentNum'];
$dbpass = $row['password'];
$dbDOB = $row['DOB'];
$dbfName = $row['FirstName'];
$dblName = $row['LastName'];
}
if($dbpass){
if($getuser === $dbusername && $dbpass === $getpassmd5){
$_SESSION['username'] = $dbusername;
$_SESSION['fName'] = $dbfName;
$_SESSION['lName'] = $dblName;
$_SESSION['type'] = "student";
header('Location: ./dashboard.php');
}
else{
echo("<h4><center>You have entered incorrect login credentials</h4></center>");
}
}
else{
if($getuser === $dbusername && $getpass === $dbDOB){
$_SESSION['username'] = $dbusername;
$_SESSION['fName'] = $dbfName;
$_SESSION['lName'] = $dblName;
$_SESSION['type'] = "student";
header('Location: ./dashboard.php');
}
else{
echo("<h4><center>You have entered incorrect login credentials</h4></center>");
}
}
}
else{
$query2 = "SELECT * FROM teachers WHERE username='$getuser'";
$exequery2 = mysql_query($query2);
if(mysql_num_rows($exequery2) > 0){
while ($row = mysql_fetch_assoc($exequery2)){
$dbusername = $row['username'];
$dbpass = $row['password'];
$dbfName = $row['FirstName'];
$dblName = $row['LastName'];
$dbtype = $row['type'];
}
if($getuser === $dbusername && $dbpass === $getpassmd5){
$_SESSION['username'] = $dbusername;
$_SESSION['fName'] = $dbfName;
$_SESSION['lName'] = $dblName;
$_SESSION['type'] = $dbtype;
header('Location: ./dashboard.php');
}
else{
echo("<h4><center>You have entered incorrect login credentials</h4></center>");
}
}
else{
echo("<h4><center>You have entered login credentials that do not exist</center></h4>");
}
}
}
else{
echo("<h4><center>Please enter both a username and password</center></h4>");
}
}
?>
Firstly, You should not have different <?php and ?> tags.
As its counted as a space.
<?php include('header.php');?>
<?php
session_start();
Should be:
<?php
session_start();
include('header.php');
Its adding a space in the file, hence redirection is not taking place.
Sounds like an Apache server or PHP configuration issue. On both servers, run a script with:
phpinfo();
Compare them for discrepancies. Also, check the PHP version, loaded extensions, and configurations in the .ini. It could be Apache httpd.conf, but I'm guessing on it being a php.ini issue or a PHP version issue.
Recommendation: create an autoloader to be a PHP include on line 1 of every file. Autoload your session and db and constants in there. This will ensure the session is loaded prior to outputting HTML, which seems to be where others are seeing an issue.
line 1: require_once('config.php');
Do session_start(); into your page first line
<?php
session_start();

Categories