PHP - session_id does not point the the right session_name - php

We are using a server that has several services on it. So to make sure the php sessions are not mixed, we want to use a different cookie for each service. We created a function called sec_session_start where we define the cookie (mySession) for this service. We then made a second function called start_my_session to connect to the service cookie.
Each time we try to use start_my_session, it gets the info inside PHPSESSID instead of mySession. How can I fix that.
The following function is called only at one place (when the user logs into the system).
function sec_session_start() {
$secure = false;
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate the safe session (ini_set)");
exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name('mySession');
session_start(); // Start the PHP session.
echo session_id(); // USE AT THE MOMENT FOR DEBUGGING ONLY
}
The session id returned by the last instruction is the id corresponding to the mySession cookie. (I checked in the server /tmp folder and inside Chrome's resources debugger.)
The following function is called inside everyother secure page once the user is logged in.
function start_my_session() {
echo session_name('mySession').'<br>'; // DEBUG : display PHPSESSID
echo session_name().'<br>'; // DEBUG : display mySession
session_start(); // Start the mySession
echo session_id(); // DEBUG : display the PHPSESSID session id
}
As mention in comment, the session_id is still pointing to the PHPSESSID instead of the mySession.
Any advice on what we are doing wrong and how we could fix it?

This might not sound very logical and you'll think I'm nuts but:
Before you switch session names with session_name(...) (and yes, that means it's also before the session is started!)... run a session_write_close();

Related

Session variables lost on new page

I'm currently developing a web application for a client with the webspace hosted on one.com.
I've implemented my own secure login system and everything works. When I log someone in, the variables are available but as soon as I go to a new page via an href all my session variables are lost. I've tried almost everything that is recommended on similar questions but it won't work.
I can not edit my php.ini directly, this is the standard phpinfo:
I can't embed Images yet, this is my phpinfo
Additionally at the beginning of every site I call
ini_set("session.cookie_secure", 0);
Because at the beginning this was (locally) always set to true.
I initiate a secure session on every page with the following code:
$session_name = 'sec_session_id'; // Set a custom session name
$secure = true;
// This stops JavaScript being able to access the session$id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
I just dont understand why my Session variables are always lost. I would be happy about every help I can get!
Edit: Some suggestd that the last line:
session_regenerate_id(true);
Propably causes the problem but after removing it it still doesn't work. What else could it be?
I'm pretty sure this line (the bottom line) is the one destroying the session:
session_regenerate_id(true); // regenerated the session, delete the old one
Remove that line and your session should be retrained.

PHP $_SESSION working in some browsers, not others

I have a webpage that uses PHP $_SESSION variables. It works fine on my computer using Google Chrome (version 44.0.2403.157 (64-bit)), but it doesn't work for other browsers or other versions of Chrome.
What can I do to fix this? I would prefer if I could keep using $SESSION variables so I don't have to recode all my webpages, but if I must, what is an alternative?
For context: I use the $_SESSION variables to store information such as the identity of who is "logged in" to my site and products in a user's "shopping cart".
Code: I start a session like this:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
Like I said before, it works fine in certain browsers. Something is preventing it from working in others.
By "working", I mean the browser allows for the use of $SESSION variables. I do not mean the variables save across browsers.
When I check the cookies of the browser where it does not work, it says that it is storing cache, cookies, and local storage for my website.
Here a small example of my code. Here, when the login button is pressed, it checks the login credentials.
<?php
/**
*
*
*/
include_once 'db-credentials.php'; //get database credentials
$mydb2= logindb(); //login to database
sec_session_start(); //start session
//process form data
if(isset($_POST['btn-login'])) //if login button was pressed
{
$email = $_POST['email'];
$upass = $_POST['pwd'];
$row = $mydb2->get_row($mydb2->prepare(
"select * from users WHERE email='$email'"), ARRAY_A
);
if($row['password']==$upass)
{
$_SESSION['user'] = $row['user_id'];
$_SESSION['name'] = $row['username'];
echo "<script>window.location = 'http://mywebsite.ca/order/'</script>";
}
else
{
?>
<script>alert('Invalid login. Please check your email and password and try again');</script>
<?php
}
}
Now, that code runs fine. With a correct username and password, the program gets into the inner if statement and will run the echo "<script>window.location = 'http://mywebsite.ca/order/'</script>"; statement.
However, when it gets to http://mywebsite.ca/order/, it no longer has the session variables saved!
I figured it out. Before, I was calling the get_header() function before I was calling the session_start() function. This worked fine on some browsers but not others.
I changed it so session_start() is my first statement.

Keeping $_SESSION in jquery ui tabs, is this actually doable?

So I've been trying to solve this issue for a very long time now, and I'm at my wit's end.
So within a web application I'm working on, the basic idea is that the user logs in, then a session is created in $_SESSION. I can see the contents of it just fine on the index page through print_r($_SESSION).
On the index is some jQuery UI tabs, and those tabs link to some subdirectories like content/index.php or action/index.php Inside those tabs, trying the aforementioned print statement doesn't return anything at all. It's like it can't see the session at all.
On the index, I have a function called sec_session_start() that's been used, and I think there's a possibility of this being an issue. The code for that is this:
function sec_session_start() {
$session_name = 'sample'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly
);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
Looking at this, the only thing I can think of is session.use_only_cookies's INI setting being the issue for this. Could that be what's blocking me from accessing the session within the tabs? I inherited this and have no clue why it's not letting me access the session regardless.
EDIT 1:
index.php:
<?php
print_r($_SESSION); //prints everything
?>
action/index.php or content/index.php retrieved through ajax call via tabs:
<?php
print_r($_SESSION); //returns nothing.
?>
EDIT 2:
I figured out the issue. Turns out, the session was stored in a cookie and encrypted. By accessing it via session_name(); then starting a session on each page, I can see the variables.

PHP Logout won't work online

I tried to look my problem up on the internet and on stack overflow, but didn't find an answer that solved my problem. So I have a back-end system for a website I'm creating for an opensource project. I have now just finished transferring everything over to my online domain and database. After a lot of other problem solving, it works now, except for the logging out.
In my back-end header I have the following url:
<h1>Logout</h1>
The content of the logout.php page is the following:
<?php
session_regenerate_id();
session_start();
session_unset();
$_SESSION = array();
session_destroy();
header("Location: login.php");
?>
Offline, via MAMP this works without any problem. However online it doesn't destroy my session. I can still access all my session variables, which enables me to stay logged in. As I said before, I tried to look for an answer, but I don't seem to find one that fixes my problem. If anyone has a clue what might be wrong, please tell me. Thanks in advance!
EDIT:
This is how I check on every back-end page, wether or not I'm logged in:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_regenerate_id(true); // regenerated the session, delete the old one.
session_start(); // Start the php session
}
As you see, #paulprogrammer, I do something with cookies. How do I destroy it for sure when I logout?
edit(2):
Ok Thanks paulprogrammer for the pointer. I removed the cookie part from my login check function and turned it onto the following simple function:
function sec_session_start() {
session_start();
}
This doesn't create a cookie and now it does work. I tried to unset the cookie via the stuff the official php manul said # http://php.net/manual/en/function.session-destroy.php but that didn't do it. So that's why I moved to something simpler that works. As not many people besides me are gonna use the back-end and as it seems to work ok, even without cookies, I call it done. This topic can be closed :)
final edit(3):
Ok Thanks to *#paulprogrammer it works now with cookies as well. Now that I know the answer, it only seems logical that you have to do that. Stupid of me. OK so apparently I had to set the name of the session, just like i did in my session. I do this in the beginning, before i start it. The new, updated, code of the log in check function:
<?php
session_name('sec_session_id');
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
header("Location: login.php");
?>
You set the session name in your setup code, but failed to set it in the teardown code. So, during teardown PHP was destroying the default session name, not your custom session name. The custom session name is still available on the request after logout.
Simply use the session_name() function consistently anywhere session operations are being used to ensure the session management is always acting on the correct session token.
In your logout.php:
<?php
session_name('sec_session_id');
session_regenerate_id();
session_start();
session_unset();
$_SESSION = array();
session_destroy();
header("Location: login.php");
?>

Is my custom session_start() creating an entirely new session rather than resuming the current session?

It appears that my custom session_start() is creating a new session rather than resuming the current session across pages. Here's the method:
public function sec_session_start()
{
$session_name = 'sec_session_id'; //set a custom session name
$secure = false; //set to true if using https
$httponly = true; //This stops javascript being able to access the session id
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies
$cookieParams = session_get_cookie_params(); //Gets currtent cookies params
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); //Sets the session name to the one set above
session_start(); //Start the php session
session_regenerate_id(true); //regernates the session, delete the old one
}
The issue that I am encountering is in regard to the superglobal variable $_SESSION. For instance, in my login page I generate a random token to prevent CSRF attacks:
$token = md5(uniqid(mt_rand(), true));
$_SESSION['token'] = $token; //Add randomly generated token to superglobal variable
...
<input type="hidden" name="siteToken" value="$token" />
I then test for the correct token value in my php processing page:
//Check Token Values (prevent CSRF attacks)
if($passedToken != $_SESSION['token']) {
$error = "CSRF attack detected. Please close your browser and try again.";
$signIn->csrfAttackLog($username);
echo $error;
exit();
}
The problem occurs in my php processing page: Notice: Undefined index: token in...
Obviously, my session variable has not been carried over. I have started another sec_session_start() in the processing page - so it's not that I have neglected to continue the session. It seems that a entirely new session has been started. I have tested the first page by "printing" the $_SESSION value.
Any input is appreciated.
EDIT: $passedToken is correct. There is an intermediate step that equates the $_POST value to this variable.
Ok I hope I understood it right. You are trying to keep one session (with the same id, on the same cookie), just some tokens and that kind of stuff to make it more secure.
But as your last paragraph mentions, you are calling sec_session_start(); on every page request to keep the session alive, right? But did you notice that you also call session_regenerate_id(true); then? That way you delete the old session files and create an entirely new session - which will be empty.
see in the form you have name="siteToken" but in condition if($passedToken !=. I suppose should be if($siteToken !=. Also try to calls sec_session_start before if

Categories