PHP sessions not persisting outside of incognito browsing - php

I'm having a problem with session not persisting after a redirect on my website when it's not being browsed through incognito. I've tried replacing the code with a simple script that sets the session variable "test" with "asdasd".
session_start();
session_regenerate_id(true);
$_SESSION['test'] = 'asdasd';
header("Location: ../results.php");
session_write_close();
The results page is as follows
session_start();
session_regenerate_id(true);
var_dump($_SESSION);
session_write_close();
But whenever I try to run the script that sets the session, the data does not persist on to the results page. But when I tried testing it in Chrome's incognito mode, it works. I've tried clearing cache and restarting the browser, the data is still not persisting. What could be the reason for this?
Edit: I'll happily provide any information regarding the configurations if it's going to help

It could be that the Set-Cookie header isn't process if the Location header is found in the same response.
It is browser-dependent, so it may be hard to tell.

Related

making user redirect if not logged in using php sessions

I am beginner in web development and i am creating my first project. I am using XAMPP, for my php files. I have basically created app.php, sigin.php. So in order to prevent user from directly access my app.php i am using session variables in php. Hence i added the following PHP code just before my app.php.
<?php
session_start();
if(!isset($_SESSION['loginstatus'])) {
header('location:./login.php');
die();
}
?>
And i am setting my session variables in my signin.php like the following:
if($user['username'] == $username && $user['password'] == $password) {
$_SESSION['username'] = $username;
$_SESSION['loginstatus'] = 'success';
echo "success!";
header('location:../app.php');
}
Now i tried accessing my app.php without login, i am still able to access app.php. To check where is the issue i cleared my browser history and cookies, then i tried accessing app.php, then surprisingly it worked i was actually redirected to login page, but as soon as i do first succesfull login, and logout and again try to access app.php without login, i was again able to access app.php without login.
Now for some reason i feel that my browser is saving session variables too, So to check that i wrote a small piece of code and pasted in my app.php:
<?php
var_dump($_SESSION['loginstatus']);
?>
after first successful login my $_SESSION['loginstatus'] is always set to successful. Now as i said i am a beginner, what i learnt is session are stored in server side. So i am totally confused regarding this.
There is a cookie in your webbrowser "phpsessid" wich stores the id of the Session on the server.
In normal cases you destroy the Session, at logout.
session_unset(); to unset all session variables
session_destroy(); destroys the session
The Session will timeout after time X. You can change it, described here -> Link
So if you have a cookie in your Browser with a valid id of a not-timeouted Session you will always be able to log in.
So basically, going to browser setting > privacy and security > more > pre-load pages for faster browsing and searching
I just disabled this default setting from chrome, and it started working as expected.

How to completely (I mean COMPLETELY) destroy all session data and prevent cached access?

I am currently setting up a website using a pay-wall type backend that you log into with Microsoft accounts. Currently, I am using PHP sessions to capture and track valid requests.
I have managed to completely destroy all session data saved on the server as well as rename and blank the session cookies (See code below). Unfortunately, this is not enough it seems. I can still access the page by passing the old session ID through GET variable and I can still load the page. I suspect it is a cached version. I have tried adding in php headders to prevent this but its still loading!
Log out code:
<?php
if ($_POST) {
session_start($_POST["SID"]);
$_SESSION[] = array();
setcookie( session_name(), "", time()-3600, "/" );
session_destroy();
session_write_close();
echo("Session ".$_POST["SID"]." has been destroyed");
}
?>
Header code:
<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
I was expecting to be able to hit the log out button and if I tried to manually access the page by supplying the old session id by GET command, I should have been bounced by the page. Is there any way to get around this? Maybe force the page to re-query the server (if I can just get it to ping the server again I believe my php should bounce the request? I say that with some hesitance hahaha)
EDIT:
Ok, so after a whole lot of debugging, I have narrowed the problem down too my $_SESSION["IS_AUTHORIZED"] variable? This shouldn't be possible but somehow, the standalone PHP script I wrote to destroy a session when the user logs out, can run the same session_id(), but somehow cannot access any of the session variables?! if I var_dump($_SESSION["IS_AUTHORIZED"]), it spits out NULL, whereas on all the other pages, it spits out the Boolean 0 or 1?!?!?! I am very confused... I guess this is why I cant properly remove the session?
Code:
<?php
if ($_POST) {
session_id($_POST["SID"]);
echo(session_id()); //comes out as same as session origin page
session_start();
echo("|||"); //to make payoad easier to read lol
echo($_SESSION["IS_AUTHORIZED"]); //nothing... and var_dump() is NULL?
?>
EDIT 2:
Oh lord. So now after some tinkering the stand-alone PHP script works and links up to the correct session_id() and I can do the whole session_destroy(), $_SESSION = array(); bit to clear the session info. Small problem though, if I refresh the HTML page with the session_id() as a GET variable, it still loads the page? Even says the `$_SESSION["IS_AUTHORIZED"] variable I supposedly just cleared in my stand-alone script is now back and reverted to before I cleared it? That literally defeats the entire point of using sessions? help please! ( I HATE php sessions so far oh my soul!)
Destroy the session data file located in session_save_path() folder / session.save_path directive.
<?php
session_start() ;
unset($_SESSION["IS_AUTHORIZED"]);
session_destroy();
session_write_close();
$_SESSION=new array();
session_regenerate_id(true);
?>
Fixed it! Just posting for anyone else who has this issue.
Turns out it all linked back to the session_write_close() command. In my HTML page which hosted restricted content, I had PHP code which checked session variables to determine weather or not to show the page or redirect. Obviously in order to access the $_SESSION[] variables in the first place I first had to set session_id($_GET[<session id passed via GET>]), and then do the checking. Unfortunately, I never called session_write_close() so that webpage never disconnected from the session file. My stand-alone logout script WAS actually deleting the $_SESSION and unset($_SESSION[<variable name>]) WAS working. The issue is that upon the HTML page refresh, I guess it re-saved the session file all over again and effectively re-created it.
The easiest analogy I could think of to explain it would be, editing a Word document and deleting the actual file while it was open in Word, then saving from Word, effectively re-creating the document all over again.
It took me changing the save directory to where I could access it and actually monitoring how the session file changed to figure it out (Good debugging technique btw)
Hope this helps future PHP coders (Good luck, you'll need it lol)

session wiped out between pages

I'm making a login page and for some reason the session will not persist between where I set it and the page where I am forwarding to. I can comment out the header in the page where the session was initialized and see that the session has the data in it. However, when I do a print_r in the target page, the session is empty.
I have already made sure that session_start is called. There is only one domain for this site and my browser is set to accept cookies. I can forward to any other page and see the session data but just not this one.
Is there something that someone can offer to help in debugging this?
$_SESSION['auth'] = $auth;
header( "Location: /" ); // commenting this out shows the data is in fact there
I want to protect the index page so I test to see if session['auth'] is set. If not, I forward over to /user/login which allows the user to login. If successful then we forward back over to the index page where it should pass the isset session test. It fails though and there is no session data.
set.php:
session_start();
$_SESSION['auth'] = true;
header('Location: /');
index.php:
session_start();
var_dump($_SESSION);
Create these 2 files and request set.php. What do you see?
If you set a session variable, then do a header redirect, you need to add session_write_close() before the redirect or you will lose your sesson modification.
Something that I've ran in to quite a bit is accidentally redirecting from a page with 'www.' in the URL to a page without. I'm not exactly sure why it happens but for some reason the session between a site is different with and without the 'www.'.

PHP: session isn't saving before header redirect

I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database.
My code is as follows:
// session
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Then at the top of index.php after the session_start(), i have var_dumped the $_SESSION global and the userID is not in there. As i said ive looked through the PHP manual (http://php.net/manual/en/function.session-write-close.php) and neither session_write_close or session_regenerate_id(true) worked for me.
Does anybody know a solution?
Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script
I know this is an old toppic but I found the solution (for me).
I've put a exit after the header.
$_SESSION['session'] = 'this is a session';
header('location: apage.php');
exit;
This works for me
#Matt (not able to comment yet...): If:
a) It appears in the session before redirect
b) other keys work
80% of the time the problem is register_globals, and use of a equally named variable $userID somewhere (the other 19% is just overwriting in places one doesn't expect, 1% is unable to write/lock session before redirect and stale data, in which case you could try session_write_close() before the redirect). It goes without saying register_globals should be off :P
I haven't heard of this issue, but I haven't used sessions all that much.
With sessions you MUST do a few things and have a few setting setup:
cookies enabled on client side
session_start(), before anything happens
make sure you don't destroy the session(unless they want to logout)
The PHP session id must be the same (relates to cookies)
Another issue could be the $user->id is returning a reference to an object that doesn't exist on the next page. Most likely not, but make sure.
If I saw your code I could help you a lot more. But when debugging check the session key with session_id() and make sure it's the same. If you could try that then tell me I could keep helping.
I too would like to know how this ends up for when I get back into sessions.
You should start the session before using the session array.
PHP Code,
session_start();
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Have you got an session_start(); on the top?
Not tested but cant you do something like this:
session_start();
$_SESSION['userID'] = $user->id;
if( $_SESSION['userID'] == $user->id )
{
header('Location: /index.php');
}
I never have this Problem before, interesting
userID does not have any keyword status.
Only reason to me, is $_SESSION['userID'] is being overwritten or deleted somewhere.
Make sure you use session->start() in all the files you want to add/access the session.
One important thing ( which may not be applicable in your case ) is, if the session is being handled using cookie, cookie can be made to be accessible only under certain directory and subdirectories under that.
In your case anyhow, subdirectory will have access to the session.
Make sure both pages are the same php version
(php5, php4 sometimes have different session paths)
I had the same problem recently. I'm writting a customized MVC Website for school and, as everyone told, start_session() must be written in the very first lines of code.
My problem was THE LOCATION of "session_start()". It must be the first lines of your global controller, not the first lines of the view. $_SESSION was not accessible in controller's files because it was only initiated when the server render the view.
Then, I'm using session_write_close() after the header('location: xxx.php') call to keep session variables for the next request.
ex:
globalController.php :
//First line
session_start();
require_once('Model/Database.php');
require_once('Model/Shop/Client.php');
...
logonController.php:
...
//Users is validated and redirected.
$_SESSION['client'] = $client;
header('location: index.php');
session_write_close();
Hope it solved your problems.
This was annoying as hell but I finally figured out a solution.
config.php i had:
include 'session.php';
At the top of session.php, I had:
session_start();
By moving session_start() to the top of the config.php file, viola...
Problem solved!
Another option than killing your script forcefully with exit is to use session_write_close to force the changes to be written to the session store.
This should however not happen if your script is terminating correctly.
As the documentation about session_write_close states:
End the current session and store session data.
Session data is usually stored after your script terminated without
the need to call session_write_close(), but as session data is locked
to prevent concurrent writes only one script may operate on a session
at any time. When using framesets together with sessions you will
experience the frames loading one by one due to this locking. You can
reduce the time needed to load all the frames by ending the session as
soon as all changes to session variables are done.
In my case this only happened during debugging with Xdebug, when I triggered the same script multiple times and thus multiple process tried to manipulate the same session. Somehow the session could then no longer be unlocked.

PHP session destroyed / lost after header

I've got a script that sets some session values before redirecting to / using header().
I've read many posts about the $_SESSION variable being destroyed / lost after header(), even after I implemented this:
// set session here
session_regenerate_id(true);
session_write_close();
header("Location: /");
session_start() is set in the correct places, does anyone know of anything that I might be missing?
On the index.php page I have this:
session_start();
print_r($_SESSION);
// outputs nothing :'(
The code is pretty complex so will not post it all, just snippets.
I've never seen any session related issues due to using location headers - are you sure you're calling session_start on both pages?
Hmm... this answer made a lot more sense before you added the session_start bits above, and mentioned the fact that you were sure you were using session_start. :-)
header must be sent before session close
session_regenerate_id(true);
header("Location: /");
// the header must be sent before session close
session_write_close(); // here you could also use exit();
just put exit; after header :D I solved by this
After the Header redirect you need to exit the PHP script:
header("Location: /");
exit();
In the interest of closing this question, we had concluded it was a problem with the server configuration, not surprising considering the host is well known for this kind of thing.
One possible option that was not mention here and happened to me is that I was creating another session. When you're using session in php you can use only one session at a time. If you create a new session the old one is lost. This is more likely to happen when you create a session for login and maybe you want another session for something else(It's not that recommended anyway). My case was a flash() method which I used to create a session only once a post was added/updated/deleted. And use that session in the views to display a message then destroy it. Every time I created a new session while adding/updating/deleting the other session that I used for login was destroyed. This is not something that happens to often but it's possible.
I had the same problem, I found that using a function related to Session helps to ensure if you started a session or not
if(session_status == PHP_SESSION_NONE)
session_start();
You don't need to start session_start() in each page. cuz untill your browser is closed the same session remains for the entire path you have specified in php.ini

Categories