PHP SESSION variable not working at the 1st time - php

Session variables are not set at the first time. From action.php it goes to employee.php But in employee.php $_SESSION['EmpID'] shows nothing when I log in for the 1st time. If I log out and log in again then works fine. works fine in localhost.
action.php
<?php
session_start();
if(isset($_POST['UserID'])&&isset($_POST['Password']))
{
$id = $_POST['UserID'];
$pass = $_POST['Password'];
$result = mysqli_query($con,"select * from auth_det where UserName='$id' and Password='$pass'");
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_array($result);
//echo $row['UserID'];
//echo $row['Password'];
$_SESSION['UserName']=$id;
$_SESSION['EmpID'] = $row['EmpID'];
$_SESSION['is_auth'] = true;
$_SESSION['User'] = "Emp";
echo "<script type='text/javascript'>window.location.href = 'Employee/employee.php'; </script>";
exit();
}
logout.php
<?php
session_start();
session_destroy();
echo "<script type='text/javascript'> document.location = '../login.php'; </script>";
?>
employee.php
session_start();
$EmpID=$_SESSION['EmpID'];
echo "EmpID=".$EmpID;
if(!isset($_SESSION['EmpID']))
{
echo "<script type='text/javascript'> window.location.href = 'logout.php'; </script>";
}

try to move the session_start() to the action.php file.
At first connect php doesn't create a session at action.php
Then you get redirected and employee.php starts the session.
If you try this again later a session is already open so you have no problems at the action php.
Also think about switching the Javascript Redirect to an header redirect since it still works if the Client disabled Javascript

please check that you did'nt forgot to write session_start(); on the top of action.php page

Related

PHP Session Variables Not Working After Redirect

I am having an issue with the follow code. It can echo the variables before it redirects, no problem. But after it redirects, it cannot. It seems to be losing the session variables in the redirect process. Any thoughts?
Original Page:
if (password_verify($rawpassword,$row["passwordHash"])) {
session_start();
$_SESSION["email"] = $email;
$_SESSION["fname"] = $row["firstName"];
echo $_SESSION["email"];
echo $_SESSION["fname"];
header("Location: https://www.mywebsite.com/home.php");
} else {
header("Location: https://www.mywebsite.com/signin.php?addlComment=3True");
die();
}
The Following Page:
<?php
echo $_SESSION["email"];
echo $_SESSION["fname"];
?>
You should learn more about sessions to avoid making mistakes and not leaving your codes vulnerable!
Know that to work with sessions, you must start them right at the beginning of each script
Also, after you create your session, you don't need to use the 'echo' command and right after redirecting to the success page, in fact, it is on the success page that you should work with the 'echo' command, and create some variables to store the value of those sessions, to make it easier to work with, and to make the code cleaner!
Please try it:
Signin
<?php
session_start();
//Start the session in the top of the script
if (password_verify($rawpassword, $row["passwordHash"])) {
$_SESSION["email"] = $email;
$_SESSION["fname"] = $row["firstName"];
header("Location: home.php");
exit();
} else {
header("Location: signin.php?addlComment=3True");
exit();
}
Home
<?php
session_start();
session_regenerate_id(true); //It can help you to protect against attacks, try to learn it!
$email = $_SESSION['email'];
$first_name = $_SESSION['fname'];
//If the user try to access the page without make login, then redirect to the signin page
if(!email || !first_name)
{
header("Location: signin.php");
exit();
}
//Test the sessions variables
echo "Welcome, you're logged in! I know your first name is: {$first_name}";

I am trying to redirect my page through header function but it will not work rather my query is working ...why?

This is my index file:
session_start();
include_once 'conn.php';
if(isset($_SESSION['hell'])!="")
{
header("Location: home.php");
}
if(isset($_POST['Login']))
{
$email = $_POST['email'];
$pass = $_POST['pass'];
$res=mysql_query("SELECT * FROM studentreg WHERE email='$email'");
$row=mysql_fetch_array($res);
if($row['password']==$pass)
{
$_SESSION['hell']=$row['stu_id'];
header("Location: home.php");
}
else
{
echo "hello"."<br/>";
echo $row['password']."<br/>";
echo $row['qualification'];
}
}
This is my home file:
session_start();
include_once 'conn.php';
if(!isset($_SESSION['hell']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM studentreg WHERE stu_id = ".$_SESSION['hell']);
$sturow=mysql_fetch_array($res);
echo "welcome";
It will not work rather my query is working …why?
What is the error message? Add ini_set('display_errors', 1); at top of page to check.
Maybe there was text printed before the header not letting it redirect?
Are there spaces before the php opening tag?
Is session variable hell exist from another page?
You add this line at start the page
ob_start();
and you add the this code after header function
exit;
Try this code:
echo "<script>window.location='home.php'</script>";

session data not displaying on logging in once but its displaying once logging out and logging in again

session data not displaying on logging in for the 1st time but its displaying once logging out and logging in again.
Anything can i do to display session data on example.com/page2.php on logging in for the first time ?
example.com/page1.php
<?php
session_start();
$_SESSION['id'] = 1;
$_SESSION['name'] = 'dummy name';
$_SESSION['email'] = 'dummy#dummymail.com';
header("Location: http://example.com/page2.php");
?>
example.com/page2.php
<?php
if ($_SERVER['HTTP_REFERER'] == 'http://example.com/page1.php' )
{
ob_start();
session_start();
echo $_SESSION['id'];
echo $_SESSION['name'];
echo $_SESSION['email'];
}
?>
<a href = 'example.com/logout.php'>Logout</a>
example.com/logout.php
<?php
session_destroy();
header("Location: http://example.com/page1.php");
?>
You should call
session_write_close();
before
header("Location: ...");
to ensure that the session data set in page 1 is written to disk before page 2 is requested.
In addition, it seems that using
header("Location: ...");
on page 1 will leave the $_SERVER["HTTP_REFERER"] value unset on page2.php. I tested this by changing page2.php to
<?php
echo "<pre>";
echo htmlspecialchars(print_r($_SERVER, true));
echo "</pre>";
if ($_SERVER["HTTP_REFERER"] == "http://example.com/page1.php")
{
session_start();
echo $_SESSION["id"];
echo $_SESSION["name"];
echo $_SESSION["email"];
}
?>
Logout
If you try the same you may see that
[HTTP_REFERER] => http://example.com/page1.php
is not listed in the $_SERVER array on page 2.
On page 1, just to test, instead of using
header("Location: ...");
try using
echo 'Page 2';
and you should find that when you request page1.php then click on the Page 2 link, $_SERVER["HTTP_REFERER"] value will be set on page 2.
So is seems that your problem may include redirection not setting $_SERVER["HTTP_REFERER"]. Once you change your scripts to resolve this issue you may have a better change or sorting out the session issue.
You might like to try
page1.php
<?php
session_start();
$_SESSION["id"] = 1;
$_SESSION["name"] = "Dummy";
$_SESSION["email"] = "dummy#example.com";
session_write_close();
header("Location: page2.php");
?>
page2.php
<?php
session_start();
if (isset($_SESSION["id"]) && ($_SESSION["id"] == 1))
{
echo $_SESSION["id"];
echo $_SESSION["name"];
echo $_SESSION["email"];
echo 'Logout';
}
else
{
echo 'You are not logged in. Login';
}
?>
logout.php
<?php
session_start();
$_SESSION = array();
session_write_close();
echo 'You have been logged out. Login Test login status';
?>
I know this is necroing a 4 year old thread, and you were not having the exact situation but here's what I found:
I was having a problem with my welcome message saying 'Welcome, [user]!'. I couldn't get it to display until I logged out and logged in again, similar to your question title.
<?php
//says "Welcome, (whatever the user's name is)!"
$welcomemessage = "Welcome, " . $_SESSION["user"] . "!";
if ($_SESSION["loggedIn"] === 'y') {
echo $welcomemessage; }
?>
On my change username page, I changed the session variable to my new username, like so:
$_SESSION["user"] = $newusername;
which is changing it from the initial username, since your old username would be set as the current session variable even if you've changed it.
So, if I change my username from John to Jeff, anything which would mention John will be changed to Jeff immediately as the 'new username' variable is displayed, rather than having to log out then log in for the code to take your new username from the database and display it.
I know this won't help you as it's been 4 years, but this was the closest question I could find to my problem and wanted to share my simple solution for anyone else who looks this up :)
You forgot session_start() on your logout.php.
<?php
session_start(); //<------- Here
session_destroy();
header("Location: http://example.com/page1.php");
?>
and comment this on page2.php
<?php
if ($_SERVER['HTTP_REFERER'] == 'http://example.com/page1.php' )
{
ob_start();
//session_start(); <----- Comment this as shown
echo $_SESSION['id'];
echo $_SESSION['name'];
echo $_SESSION['email'];
}
?>
<a href = 'example.com/logout.php'>Logout</a>

Alternative to PHP deprecated function session_is_registered() for logout.php file

I'm trying to create a simple member login site, and I was following along with a tutorial online. However, a deprecated function is used. Here is the code.
<?php
session_start();
session_destroy();
if(isset($_COOKIE['id']))
{
//remove cookie
setcookie("$id_cookie", '', time() - 50000);
setcookie("$pass_cookie", '', time() - 50000);
}
if(!session_is_registered('username'))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>
I also tried !isset($_SESSION['username']), but every time I try to log out, I just receive the 'Sorry we could not log you out' text.
Here is the part of my login.php file code where I set the sessions:
//member does exist, start sessions
$_SESSION['password'] = $password;
while($row = mysql_fetch_array($query))
{
$username = $row['username'];
$id = $row['id'];
}
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
Any help would be great!
Don't use
session_is_registered
use
if (isset($_SESSION['SESSION_VARIABLE_NAME']))
You may add "session_unset();" before "session_destroy();"
session_destroy() delete the session file and release the session id, but keep the $_SESSION variable in memory.
use this with isset
if(!isset($_SESSION['username']))
Try this
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
Check where the the SESSSION is stored or not.
Try this code in your log out script
<?php
session_start();
if(isset($_SESSION['id']))
{
unset($_SESSION['username']);
unset($_SESSION['id']);
}
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>

PHP unset and desroyed session starts itself

I got a little problem with my php code here... Can you please help me out?
The problem is that when i, in my logout.php, unsets and destroys sessions, it works the first time i load some of my other pages.. but when i refresh right after, the session is started again, which i dont really understand? Because i have my page to look for a session with a specific name. Here is my code:
Login.php:
<?php session_start();
//Get username and password
$email = $_POST['email'];
$password = $_POST['password'];
//Sorting special characters away, with exception of "-" and "."
stripslashes($email);
$email = preg_replace('/[^A-Za-z0-9#\.\-]/','', $email);
//Getting the password from the database
$link = mysqli_connect("****", "****", "****", "****");
if (mysqli_connect_errno($connect))
{
echo "Connection Failed!";
mysqli_close($connect);
}
$sql = "SELECT * FROM admins WHERE email = '". $email . "'";
if ($result = mysqli_query($link, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$db_password = $row[2];
}
mysqli_free_result($result);
}
mysqli_close($connect);
//Compare DB-password to entered password
if ($db_password == $password)
{
$_SESSION['admin'] = $email;
header("Location: ../index.php");
exit();
}
header("Location: index.php");
exit();
?>
Logout.php:
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Index.php:
if (isset($_SESSION['admin']))
{
echo '<div id="admin"><br>
<h3>'.$_SESSION["admin"].'</h3>
<span>Admin panel</span><br>
<span>Log out</span>
</div>';
}
And yes, i got session_start() on top of every one of my pages.
As you can see in the index.php, i want some code to be written if $_SESSION['admin'] is set. And when i destroy the session in my logout.php, and goes to index.php, it works the first time i load the page. But i i refresh, the code reappear, which means the session must have been set again, somehow! But i dont know why? Please help!
EDIT: I have put the whole code of the login.php now. The rest of the other 2 pages, is pure HTML. What i have posted is all my PHP code!
It might because of the PHPSESSID cookie. just try it by removing PHPSESSID cookie from browser
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
setcookie('phpsessid','value',time()-1);
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Once you refresh, your following condition staisfies:
if ($db_password == $password)
connection establishes, session is created and you are redirected to index.php from login.php.
Change this condtion and your script works

Categories