In PHP, when navigating from one page to another, the session is not logging.
suddenly the $_SESSION["username"]; that is sent from the login screen,
in :
session_start();
$_SESSION["username"]=$username;
echo $username;
echo $_SESSION["username"]; // THESE 2 ECHOes WORK
When in the index:
<?php
session_start();
echo $_SESSION["username"];
// THIS ECHO IS BLANK ALREADY TRIED IT WIWH OTHER ECHOES THE PAGE WORKS
?>
your calling session_start(); too many times.
Try a simple check if session is started
ex:
// start session if not session_id not present
if(session_id()=='') session_start();
You can also check if there is a session variable with:
if(isset($_SESSION['username']) && $_SESSION['username'] !== "") // this checks if its set and does not equal nothing
{
//do your code
}
else
{
//reset $_SESSION['username'];
}
Related
I have to pages that requires login. admin.php and rehab.php. upon login i set two session variable:
if($row[2]=='Admin'){
// Initializing Session
session_start();
$_SESSION['user']=$username; // Initializing Session user
$_SESSION['dept']='Admin'; // Initializing Session dept.
header('location: admin.php');
}
else if($row[2]=='Rehabilitation Services'){
$_SESSION['user']=$username; // Initializing Session
$_SESSION['dept']='Rehabilitation Services';
header('location: rehab.php');
}
This both pages have include header.php (where username can be seen). I've decided to put the session validation in header.php:
session_start();
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: login.php");
}
so whenever someone will access admin page by typing in in the browser (../admin.php) or (../rehab.php) it will be re-directed to the login page.
My problem is, if a REHAB user is now logged on. (../rehab.php) whenever i try to change rehab.php to admin.php IT CAN STILL BE ACCESSED! i try putting this in the top of admin.php but it doesn't seem to work.
if ((isset($_SESSION['dept'])) && $_SESSION['dept']!='Admin'){
session_destroy();
}
In the rehab.php page, if you want to restrict access only to those who are logged in and have a 'Rehabilitation Services' dept assigned, you should use:
session_start();
if(!isset($_SESSION['user']) ||
(isset($_SESSION['dept']) && $_SESSION['dept']!='Rehabilitation Services')){
header ("Location: login.php");
}
This should work; there are couple of things I've noticed and you're code structure is good as far as what you're trying to accomplish:
session_start(); // Have this as the first thing on the script
// at the top before anything else above it
if($row[2]=='Admin'){
// Initializing Session
session_start(); // Remove this; you need to put session_start
// at the top of the script
$_SESSION['user'] = $username; // Is the $username coming in
// from $_POST? Should this be
// $_POST['username'] unless you
// defined it beforehand
$_SESSION['dept'] = "Admin"; // Initializing Session dept.
// This is ok.
header('location: admin.php');
} elseif($row[2] == "Rehabilitation Services"){ //Keep this in one line
$_SESSION['user'] = $username; // Initializing Session
$_SESSION['dept'] = "Rehabilitation Services";
header('location: rehab.php');
}
session_start();
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
if (!isset($_SESSION['user']) && $_SESSION['user'] != '') {
// corrected line above, you can also use empty() function
header ("Location: login.php");
}
if ((isset($_SESSION['dept'])) && $_SESSION['dept']!='Admin'){
if (isset($_SESSION['dept']) && $_SESSION['dept'] != 'Admin'){
//Corrected line above
session_destroy();
}
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>
I have made a login and register system, which works flawlessly, and I am very proud of, but I cannot seem to get a logout function working.
My login system basically takes the database and scans it for rows that have both the username and password specified, and if it does, then it makes $_SESSION['loggedin']=1; and if it fails it makes it equal to 0.
Once the user is done, he/she clicks on a link that redirects to logout.php, and that is where the issues start. I have put session_start(); at the beginning of each page, but session_destroy, session_unset, and combinations of the two cannot seem to kill the session.
So I am wondering, is there a way that upon loading logout.php, it sets the $_SESSION['loggedin] to 0, and then redirects back to index.php(my homepage)? Which means it doesnt kill the session, but it would effectively log the user out. Any help is appreciated.
// Four steps to closing a session // (i.e. logging out)
// 1. Find the session
session_start();
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
if session_destroy doesn't work, use instead:
unset($_SESSION['put your session in here']);
// logout.php
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 1) {
$_SESSION['loggedin'] = 0;
header('Location: index.php');
}
It redirects the user to to index.php, if $_SESSION['loggedin'] equals to 1, and sets $_SESSION['loggedin'] to 0.
I suggest you to have 3 files
1) login.php
session_start();
/*if user $_POST username and password is correct then*/
$_SESSION['loggedin'] = 1;
?>
2)logout.php
<?php
session_start();
unset($_SESSION['loggedin']);
$_SESSION['loggedin'] = 0;
?>
3)checkLogin.php
<?php
session_start();
if ( isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 0 )
{
echo "<script type='text/javascript'>alert('You need to login !')</script>";
echo '<meta http-equiv="Refresh" content="0;URL=index.php" />';
flush();
exit();
}
?>
with 3 files if you want to control some page that require login before access you just include(checkLogin.php);
e.g. index.php is not require login then not include(checkLogin.php);
but memberProfile.php is require login before then include(checkLogin.php);
I've got a login script that puts user details into session variables. Today I moved the website to a new host, and now my coding doesn't work. This is the best I can do, and it still doesn't work
main_login.php:
(script above here gets all the $info from the database. So far it is working)
if($count==1){
session_start();
$_SESSION['username'] = $info['username'];
$_SESSION['given'] = $info['given_name'];
$_SESSION['family'] = $info['family_name'];
$_SESSION['profile'] = $info['profile'];
$_SESSION['adultchild'] = $info['adultchild'];
$_SESSION['id'] = $info['id'];
header("location:welcome.php");
}
welcome.php:
// Check if session is not registered , redirect back to main page.
// Put this code in first line of web page.
session_start();
if(!isset($_SESSION['username'])){
header("location:main_login.php");
}
The trouble is when I print any of the session variables nothing happens. I've even tried doing a var_dump($_SESSION) but it comes up as an empty array. Frankly I've spent all day on this and am stuck.
session_start();
if(!isset($_SESSION['username']));
header("location:main_login.php");
}
change to:
session_start();
if(!isset($_SESSION['username'])){
// ^ typing mistake
header("location:main_login.php");
}
I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks
<?php
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
session_start();
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
You have to have session_start(); on the very top of your code, after <?php. Since you are checking if the session is set without starting the sessions, your code will fail.
Is has to be like this:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
It's because you're always looking in $_POST for your user data.
Bring the session_start() out of that condition:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
You said that you called session_start() at the top of your login page, but you did not mention your other pages. session_start() needs to be called at the top of every page in your application. I generally put my session_start() logic, along with a snippet of code for logging the user out after a period of inactivity, in an include file and then include it at the top of every page.
<? session_start();
if (isset($_SESSION["last_activity"]) && (isset($_SESSION["username"])) && ((time() - $_SESSION["last_activity"]) > 900))
{
unset($_SESSION["username"]);
}
else
{
$_SESSION["last_activity"] = time();
}
?>