$_SESSION variables not transferring from page to page - php

If I write the following code:
session_start();
$_SESSION['user_id']='daniel';
the variable stays fine as long as I'm on the page on which it was created, and the second I try to call $_SESSION['user_id'] from another page, I don't get a response.
Can anyone tell me what mistake I'm making?

You should be using session_start() on every page you want to use sessions on.

As long as:
You are doing session_start() on the other page. Note: you don't make this call once. You do it on every page that wants to access the session information;
The other page can see your cookie from this site (ie sufficiently similar domain); and
The other page is running on the same server.
then it can see it. Construct a simple test case and verify this and then work out why what you're doing is different.

You must have session_start() on every page

Ensure that the PHPSESSID cookie is actually being set, and that no headers / content have been sent before you call session_start()

Related

$_SESSION, PHP, iframe, not getting the SESSION variables

I m creating a very simple PHP-based program for warehousing but quite complicated back-end process.
So here is the situation:
I have the login page that directs to authorization page where it set the session_name for the first time, session_start() and set the session variables.
After the authorization page, it goes to the main.php page that is a table with left hand side for menu (links) that I also did session_name() <-- same name as the one created from (1), and start the session.
On the right hand side of the main page is the iframe that display the page when user click the links on the left. I also did session_name() <-- same name as the one created from (1), and start the session.
Problem:
main.php is ok, it reads the session variable perfectly, but the iframe couldn't get the session variables (i tried to print_r($_SESSION), and came up empty). I tried var_dump(session_name("abc")), where "abc" is the session name that i used in (1), and it does show "abc", tried (isset($_SESSION)) and returns true... so I don't know what am I doing wrong...
EDIT:
I m sorry guys, i think i may have found the culprit... it is a logic error on my side... i have this condition to check every php page i created to destroy session when the user level is not authorized to use this current page. My bad.. thanks so much for your help guys!!
Make sure that session_start() is on all the pages:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
see PHP manual reference
To control the contents of the $_SESSION try to put in all ifreame pages the code:
<?php
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
Did you use session_start() at the top of the page in both the iframe as well as main.php?
You need to put session_start() on the top of the iframe too.
This might solve your problem: php session & iframe
Additionally: Nothing is simple if you're using iframes to display large portions of your webiste. You might want to consider not using them.
I had the same problem with multiple iframes on one of my PHP webpages.
In my case, some AJAX calls to PHP endpoints were being made to www.example.com when the page was loaded using http://example.com. If you are NOT consistent with the domain path, you may have session issues since a request from www.example.com is technically from a subdomain as oppose to being made directly from http://example.com. You can avoid this problem altogether by always using relative paths to your PHP based API when making AJAX calls in JavaScript.
I found this was the case by inspecting my cookies in Chrome. I noticed two different cookies with a different PHP session ID in them. One was set for www.example.com while the other was set for example.com
As mentioned in some of the other answers, you can always set the session cookie domain to work on all of your subdomains along with your main site by using the following:
ini_set("session.cookie_domain", ".domain.com");
PHP by default will set a new session per domain / subdomain. Hope this helps!

Session doesn't get passed from page to page with eval()

I'm trying to get a session to pass from page to page while using eval(). Basically I have one page that handles all other requests and just gets the pages output via an eval() call.
Everything works fine, but for some reason the session information keeps resetting on every refresh. The login system, which also uses sessions, doesn't reset with every page refresh, though.
If you go to http://fretfast.com and view the source code, you can see the contents of $_SESSION starting on line 221.
My question is, how does the login system still work but the other session information keeps getting reset? The firstActivity and lastActivity variables are set on the configuration page that is included on the main file which handles all requests. These only get set if a session has not already been started, like so:
if ( session_id() == '' ) {
session_start();
// set other $_SESSION['trail'] variables
}
The requests and requestTimes variables are set inside the object that retrieves a given page's contents via eval().
If anyone has any idea what the problem may be or needs any information I would be glad to provide it. Thanks in advance.
Your check never evaluates to true, so the session_start() never executes.
Unless you specifically changed (or emptied) the session id (either by code or in your php.ini), it defaults to PHPSESSID (and a quick firebug check to your url confirms that).
Skip the check altogether, and just issue the session_start() at the beginning of your file.
P.S. Why do you use eval() ? NEVER use eval() !

PHP Session variable not accessible

I am having a problem in accessing a session variable.I have one page lets say test.php, when i use print_r($_SESSION) here, it prints all the session data.But when i use Redirect then i am unable to access session data on test2.php i-e print_r prints empty array, even though i have session_start() at the top of my script.
Then i tried header("Location: test2.php") and now session data is accessible.
But i want the page to be redirected on onClick of a button.
Please help ..
Make sure you have session_start(); in the head of both files and you're not browsing in a private browsing mode.
I was using the path http://localhost/project/orders.php in href then i changed it to just orders.php and it worked
Cheers
Sometimes, accessing with http or https or http://www can make the difference of variables in session being accessed or not. Please browse through all in order to be certain, as sometimes saved urls are with www whereas the session is created with simple http. It matters in session accessibility.

PHP + Logout Member when Session Expires

I've a site where people login and a SESSION is created.
I have noticed that if you leave the site for long enough (not sure exact time frame) the session ends but the members is still in the site. They can still click and navigate around and I believe this has resulted in some meaningless data in the DB as SESSION variables like userID don't exist.
I was looking for advice around logging users out when the SESSION ends.
I have looked at code like this - any better ideas?
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
Is there a better way to write the above code?
Where should this code be placed? Just on the navigation menu or really on any place a user can click?
Finally is there a way to understand when the SESSION naturally expires - is there a SESSION variable I can print to screen to see the timeleft etc?
thanks
You need to validate the session, you already headed into that direction with your code, but it's not enough:
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
It's not enough because $_SESSION[] exists automatically after the session is started (the session mechanism in PHP, see session_start).
Instead, if you have saved the userID inside the session, check that one:
isset($_SESSION['userID'])
If the session really expired, it should not be set.
I agree with the above answer. I would say it depends on how your application is architected to say where this belongs. before there is any output to the screen I am assuming your calling session_start, then immediately check for a session variable such as userID that gets set after a user logs in. if it's not set redirect setting a header for location to your login page. you could also write some js that checks the session cookie for a value at a specified interval(I believe, it's been a while so test it out), then when the variable isn't present you can redirect to the login page. a third way would be for the js code to make an XHR call to a php script to check out the session for you.

PHP $_SESSION not working as expected

I have a PHP website I'm maintaining and I've confirmed that this worked at one point.
We have a website utilizing a login system which stores a logged in user's information in a $_SESSION['user'] variable. The site used to log out the user when clicking /logout.php which essentially removed that portion of the session, then header() redirected to the homepage.
As of recently, the /logout.php file with session_start() at the top somehow doesn't see the session information when print_r() is used to output it for debugging purposes.
If I go to another page, I see the session info just fine, but not on the logout page...which is exactly why I cannot remove the session info, because it's not accessible.
I thought $_SESSION was global on the site until the browser was closed. I've never had this happen and I know the session instance was started on this page, so it's weird that it's not showing me the session data.
Any ideas? I'm totally stumped on this one!
Code: /logout.php
<?
#session_start() is inside this file
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/config.php');
unset($_SESSION['user']);
header("location: /");
exit();
?>
The checking of $_SESSION['user'] is site-wide and I call to various items below it when needed for different things. Someone else built this site and I'm trying to debug why it's not working for them all of a sudden.
If the domain/subdomain is the same as the rest of the page, I would say this sounds like a typical session vs. output error. Make sure you have enabled all errors, and display them, as you might have printed output to the client before calling session_start(). This will break the function and making sessions unavailable.
To fix the problem(if it is the case), you should remove all output before session_start. Even a space before <?php will be considered output by Apache(and other). Also make sure you have disabled BOM(Byte Order Mark) in the document(any decent editor will let you change this, just look for something like "Current file setings").
Always remember the first line of your PHP code should be session_start(); and nothing else. If all your going to do is unset the session variables and destroy the session, Try removing the require_once($_SERVER['DOCUMENT_ROOT'].'/includes/config.php'); and add the session_start() and the session_destroy() at the end of the logout.php file and see if it works.
Are you accessing logout.php from the same exact domain that you set the session to begin with (i.e. example.com vs. www.example.com/logout.php)
As for just unsetting specific session data, it would be best to call session_destroy() and then unset your cookies to kill the session.

Categories