PHP Session working but hidden in Chrome Resources tab - php

I have an odd problem with PHP Sessions (using php 5.6) both in localhost and own webhost.
I create a new session, I echo it and it gets displayed. However when I head to Resources -> Cookies -> localhost/mydomain.com I only see PHPSESSID, and not the session I created.
<?php
session_start();
$_SESSION['test'] = "test";
echo $_SESSION['test'];
?>
Picture right after I run the code above:
What is wrong with what I do? Or is it a PHP or Chrome related issue?
Thank you.

PHP Sessions are server-side. It's not an issue, it's by design.
On the client side, meaning chrome or any other browser, there is only the session id. That's what is stored as "PHPSESSID"-Cookie if not modified. Everything else stays on the server. You can't access this from chome.
To see the session-data, you can create a php site with this content:
<?php
header('Content-Type: text/plain; charset=utf-8');
session_start();
var_dump($_SESSION);
Edit: This simple example only works if you don't save class instances inside your $_SESSION. In this case the classes must be defined before session_start().

Related

App using old session file after session_regenerate_id()

session_start();
$_SESSION['user_id'] = 0;
session_regenerate_id();
$_SESSION['user_id'] = 5;
After running the following code, why is my $_SESSION['user_id'] still 0 when I access it later? Am I misunderstanding how session_regenerate_id() is supposed to work? Or is it an issue that I need to address elsewhere?
I can see that two session files have been created in C:\xampp\tmp, but I don't understand why the old file is being used.
My example is me trying to understand why I could not access $_SESSION['user_id'] that I would set after running session_start and session_regenerate_id at the very beginning of my .php file:
session_start();
session_regenerate_id();
$_SESSION['user_id'] = 9; // i am unable to access this because my app is using the old file
Appreciate any help with this.
Didn't you check the session.use_trans_sid php.ini option?
In my php.ini, I have session.use_trans_sid=0 and another suggestion mentioned i do the following as well session.use_strict_mode=1. Still not working after these two edits.
Note: i assume that they are 2 different https/http calls (the two
codes starting with session_start() ... ) Can you see what all is
stored in the 2nd file in the Session before and after you do the
session_start? you can do a print_r($_SESSION) and do it before you
regenerate as well I bet there is some code in between your lines that
you haven't shared, is doing something to the session_start
I actually simplified my code down to the example in my post, and you can see it here. This way, we are not worried about any other code.
I cleared my tmp folder and ran the code. Here are the resulting files with session_regenerate_id() commented out:
First File - https://pastebin.com/mBhQCrF3
addrelease.php output is 9 for 'user_id'
I commented out the line that sets the 'user_id' to 9 to see what happens next time I log on
Second File - https://pastebin.com/QNJ6S7sY
As expected, a new file with 8 as 'user_id'
Now I will clear the tmp folder (and restart server) again and do the same with session_regenerate_id() in the code. More specifically, this is what loginuser.php will run now:
session_start();
$_SESSION['user_id'] = 8;
session_regenerate_id();
$_SESSION['user_id'] = 9;
$response['success'] = true;
$response['username'] = "test";
echo json_encode($response);
exit;
This time, since we regenerate the id, there should be two files after loginuser.php is finished. I can't tell which one was created first, but we can see that one has 'user_id' set as 9 while the other has 'user_id' at 8:
File 1: https://pastebin.com/ba1vAmjd
File 2: https://pastebin.com/H9kDfdvt
After this, the output given by addrelease.php once it's finished is 8.
With the following change to loginuser.php, we can also get an idea of what 'user_id' is before it exits and addrelease.php runs the second session_start() call:
session_start();
$_SESSION['user_id'] = 8;
session_regenerate_id();
$_SESSION['user_id'] = 10;
$response['message'] = $_SESSION['user_id'];
$response['success'] = false;
$response['username'] = "test";
echo json_encode($response);
exit;
I clear tmp folder and restart servers again. This time, 'user_id' output is 10. So we can see that loginuser.php is using the correct file, while addrelease.php does not:
File 1: https://pastebin.com/7MpRMbge
File 2: https://pastebin.com/p6RUxH8F
Hopefully I have supplied enough in response to your comment.
EDIT: Also, I don't know if this is significant, but there is a another activity (dashboard activity) between my login activity and my add release activity that does not trigger a .php file.
I think i know the core issue and have the solution as well.
From the json_encode, i assume that some frontend is querying these php files and a json response is sent. So, the session is being written to multiple times.
After writing to the session, IN EVERY FILE that you write sessions to, but PER HTTP/HTTPS request, please do an explicit session_write_close() https://www.php.net/manual/en/function.session-write-close.php .
So, what i mean is that let us assume you have frontendpage1.php that has the html for the user. If you are writing to sessions in this file, do a session_write_close() at the end. Further, if, as a result of an ajax call or something, you have file1.php, file2.php and file3.php used, where they are all writing to the session, do session_write_close() at the end of the last write of the session.
I remember reading that this good practice when sessions are written to frequently.
I had a similar issue with sessions and this worked well
Remember to do a session_start() at the start of each unique browser request/ajax request
EDIT
2nd Option: I think you have a corrupt cookie PHPSESSID . If you try with a browser that doesn't have any cookies set (for the server that is hosting your files), i bet you see the right session values.
Another way to test is, use the same browser, but just add The only thing I can think of is a corrupt cookie PHPSESSID (the default) or whatever cookie you are using, but just add session_name("myStackOverFlowID"); before session_start(); in both these files. the new session_name is not highly recommended: it is just to test.
EDIT: another option
Do the session_write_close() before regenerating the ID
Thanks
Finally, we know that an Android App is involved!
Check if any part of the App code is storing cookies, etc., in cache
Track time using hrtime(true); (recommended instead of microtime for accuracy) see https://www.php.net/manual/en/function.hrtime.php
If possible, clear out the App data on that android phone and test on a different android phone as well
So, after seeing that session was working correctly on my PC browser, I assumed from there that the issue was perhaps purely with how I set up something in my code for the Android app.
As it turns out, my CookieJar implementation was non-persistent. Using PersistentCookieJar instead, I was able to have cookies persist between my activities on the app.
So for anyone having a similar issue, I would suggest reading through this thread and if nothing works, be sure to check your cookie management implementation for the app.

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)

PHP Session Variables not Giving a Value

Found the solution. Solution at the bottom of the post
I have some code in php using sessions (I'm just testing them out - I want to use them in a login system).
test1.php:
<?php
session_start();
$_SESSION["test"] = "works";
echo $_SESSION["test"];
?>
test2.php:
<?php
echo $_SESSION["test"];
?>
test1.php output the correct value (where I wrote echo $_SESSION["test"];), however when I switch to test2.php, there's nothing. I have checked the cookies (both websites have the same session cookie). Could the problem be a server error?
Found the solution. A simple error like that can create a big problem. At the time, I did not realize that I had to have a session_start() at the beginning of every php webpage that I used session variables in.
There must be a sesssion_start(); at the beginning of EVERY php webpage that you are using session variables in

How to access SESSION variables throughout PHP files?

file1.php
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['pass'];
$_SESSION["email"] = $email;
$_SESSION["pass"] = $password;
//echo $_SESSION["email"];
header("location:file2.php");
?>
file2.php
<?php
session_start();
$email = $_SESSION["email"];
echo $_SESSION["email"];
?>
I want to display the email the user logged in with. The error says "Undefined index email" at the second line in file2.php. Everywhere I've looked says to put session_start() at the top of every file, and to create the session in file1.php, then access it via line 2 of file2.php.
The only thing I can think that is making this not work is that this is not using HTML. I have an android app where the user enters their email and password. My app hands off the credentials to file1.php. I know it hands off correctly because if I uncomment line 6 of file1.php, the echo response works correctly. It for some reason, will not echo in file2.php.
The reason I need this to work is because I want to be able to use the email session variable in any php file (for logging out, display info, etc), and if I can't get it working in this simple example I will have no where to go.
There are several similar questions on the site (e.g. this). They suggest to use the isset method to ensure your session variable is available.
In your case, it could be added before the header call in file1.php, so
if (isset($_SESSION['email'])) {
header("location:file2.php");
}
The sessions in PHP by default are cookie based, your APP don't use cookies, you need to implement another method session like a self generate token against a database, maybe use a REST framework.
Another solution can be emulate the cookies with headers but I don't know if that is possible in Android
Session works by cookie support, does your android app's request class supports this ?
It seems your client sends request to file1.php then server responses with session id in cookie, then your application redirects to file2.php. In normal way browsers sends previous session id to tell server which session belongs itself. Please check that you are sending this cookie while requesting file2.php

Sharing session instances in PHP

I want to use session in PHP. But its showing some problems in my scenario.
I want to share same session in 3 different PHP files.
./sessionTest/testing1.php
./testing2.php
./testing3.php
if i store some information in $_SESSION in testing1.php, i cant access the same information in other 2 files
what should i do to make these 3 files share the same session instance?
Is there any other(except cookie) to make this possible?
P.S. These 3 files are executed by different calls, cant include one file into another using include() or require() functions.
Added session_start() at the top but still doesnt share the same session.
Like so :-)
//<-- testing1.php -->
<?php
session_start();
$_SESSION['value'] = "Text!";
?>
//<-- testing2.php -->
<?php
session_start();
echo $_SESSION['value']; //Text!
?>
See this tutorial about: PHP Sessions
Maybe it can help you to understand the working with sessions
Get hold of iehttpheaders for MSIE or web developer toolbar/firebug for Firefox and check to see if a cookie is being dropped by your PHP code / presented. Also check the path and flags on the setcookie header.
Are PHP errors disabled? If so, you could have a problem in code and just not seeing it? I've had this happen where I had some white-space in the output stream before starting the session, meaning that the session broke because the session header wasn't sent first. Of course not having php errors displaying it wasn't obvious as to why the variables were null.
Just an update as I was having some issues here. Using session_name() can be helpful if the site has multiple sessions/cookies. Look in your browser preferences to see what cookies the browser is storing. I've found you have to flush these cookies a lot to see what is going on if you are using different sessions.
<?php
session_name('mySession');
session_start();
$_SESSION['value'] = "Text!";
?>
<?php
session_name('mySession');
session_start();
echo $_SESSION['value'];
?>

Categories