PHP session is not resuming - php

I have a problem with sessions in PHP. When I use session_start(), and assign a value using $_SESSION['x'] = "Y", the value is gone after refreshing the page (session is empty). echo session_id(); always shows a different value. I also tried using exit() after assigning the value. This probably means that the session is not resumed, a new one is created instead. What can I do?
EDIT: I am using cloudflare, might this be a problem?
My code:
<?php
session_start();
echo session_id();
exit();
It always shows something different. PHP session is created in /var/lib/php/sessions, but php session cookie is not set, cookies are enabled in my browser. I have also tried a different browser.
EDIT 2:
When I refresh the page, a new session file is created.
The only cookie is __cfduid. I think it's something with cloudflare.
EDIT 3:
I have also tried without cloudflare. My PHP sessions settings are default.

session_start(); echo session_id(); $_SESSION['x'] = "Y"; echo '<br>'; echo $_SESSION['x'];
if your cookies are disable then your session_id() create every time new. please make sure cookies are not disable.

It's old, but the problem is very simple:
Your cookie need to be marked as secure!
Look this solution:
PHP Session ID changing on every request

Setting $_SESSION value NULL is working on this example.
<?php
session_start();
function errorMassage()
{
if (isset($_SESSION["errorMassage"])) {
$outPut = "<div class =\"alert alert-danger\">";
$outPut .= htmlentities($_SESSION["errorMassage"]);
$outPut .= "</div>";
$_SESSION["errorMassage"] = null;
return $outPut;
}
}
?>

Related

Telling a php session's name?

I installed a pre-built forum on my website and I want (in a diffrent page) to check if the forum's session is active.
Something like :
if (isset($_SESSION['forum'])) { echo "Session is active!"; }
Problem is - I don't know the sessions name...
Tried downloading some chrome add-ons for session managing but I can't get the name of the session.
Whats the right way of doing this?
Thanks ahead!
You can see the dump of $_SESSION variable
var_dump($_SESSION);
session_name() will give you the session name, that usually is defined in php.ini. By default it is always: PHPSESSID. This name is used as cookie name or as POST/GET variable name.
session_id() will give you the identifier for the current session. It will be the contents of the cookie or POST/GET variable.
Then you have $_SESSION that will contain all your session data. use print_r() to see what you have stored in it so far.
To know if session vars are set you can also just do if(isset($_SESSION)&&count($_SESSION))
try
print_r ($_SESSION);
taht way you'll see all sessions
<?php
session_start();
print_r($_SESSION);
?>
Use this to see which session variables are currently set.
You need to check that the session is currently active, and then that the forum key is defined
if ( ! ($sid = session_id()) {
session_start(); // open session if not yet opened
$sid = session_id(); // get sid as session ID
}
// $sid contains the session ID (in cookie)
if (isset($_SESSION['forum'])) {
// forum is defined
}
See also the answer from this page

Session in PHP in Social Engine

I have this query in mysql in a php page:
mysql_query("INSERT INTO tz_todo SET text='".$text."',
position = ".$position.",
user_id=".$_SESSION['user_id'].",
view_stat=0");
I tried to echo the query and the result is this:
INSERT INTO tz_todo SET text='trial text', position = 21, user_id=, view_stat=0
it seems that it can't get the session value of user_id.
And $_SESSION['user_id'] is not working in social engine. How to correct this? I also made a localhost version in my xampp and everything is fine but when I converted it into social engine, session is not working.
In any page where you are using session objects, place this code at the beginning of the file:
if(!isset($_SESSION)){session_start();}
This way if the session is not already started, it starts it; otherwise it ignores the session start if the sesion is already started.
This is important because calling session_start() if session is started already can sometimes cause errors.
That's how I get my user id through session
session_start();
$userID = $viewer->getIdentity();
$_SESSION['user_id'] = $userID;
echo $_SESSION['user_id'];
Using session to store the user_id is totally wrong. To gain a user_id try
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity(); (or $user->getIdentity if you have another user's object).
If you still need to use session for storing this data, use Zend-approach.
session_start();
$_SESSION["test"] = "hello world";
session_start();
echo $_SESSION["test"];
does above code work ? if not, check your session.save_path in the php.ini
NOTE: to retain this variable remember to call session_start() on each php script/page before calling for the variable from the session.
Yoy might be forget to start your session at the top of the page
<?php if(!isset($_SESSION)){ session_start(); } ?>
$_SESSION['user_id'] might not stored a value. check your login page (Basically after login session variables will set) or after register weather you assigned a value to that session variable..
setting a value to a session variable :
$_SESSION['user_id'] = "1234567";

PHP sessions working very well, but something's bugging me…

I've been working with PHP sessions, and everything is working fine it does exactly what I need.
Then I started to look into potential security issues further and found this:
http://phpsec.org/projects/guide/4.html
Notice that all that was being used was to determine existing session or new session 'status' is:
session_start();
...and yet I have seen this sort of thing many times before:
<?php
if (isset($PHPSESSID))
{
session_start($PHPSESSID);
}else{
session_start();
};
?>
I had assumed that this would allow some other processing on second call or that it's logic allowed the session to restart with the same session ID for a different page for example.
However I already thought that the plain session_start() already had logic to determine if a session had been established elsewhere because it 'knows' to retain an existing session ID rather than issuing a new one, unless it needs to of course!
So I tested the above and I couldn't get it to work at all.
<?php
if (isset($PHPSESSID))
{
$oldsession = "On";
$newsession = "Off";
session_start($PHPSESSID);
}
else
{
session_start();
$newsession = "On";
$PHPSESSID = session_id( );
};
echo 'ClientSessionID : '.$PHPSESSID.'<br>';
echo 'Refreshed Session : '.$oldsession.'<br>';
echo 'New Session : '.$newsession.'<br>';
?>
Either I'm missing something or this code could never have worked. The $oldsession NEVER gets echo'ed even though the session is retained. I conclude that the test on $PHPSESSID never works.
So my question is: Assuming the sample test code is syntactically correct, is it even plausible to attempt to pre-determine the session 'status' BEFORE calling session_start() ? And if so how would you go about it?
As the article goes on to show, using the (assumed) resulting session variables after a session has started is the only way to send the code in a different direction, so I'm thinking this is actually the only way to do it.
It looks like the article was written in early 2005, so perhaps the article was assuming that the register_globals setting was turned on. Earlier in PHP4, it was on by default, but it has been disabled by default in PHP5.
For your code to work, you'd need to explicitly use $_GET['PHPSESSID'] or $_COOKIE['PHPSESSID'], since the global variable $PHPSESSID is probably not set due to register_globals being disabled.
Also, note that the session name won't always be "PHPSESSID." That's default, but it can be changed in the session.name server setting or changed in the code at runtime with session_name().
session_start() will reclaim an active session if one exists. You can observe this behaviour with the following snippet:
<?php
session_start();
echo 'Current session ID: ' . session_id();
$_SESSION['previous_id'] = session_id();
session_regenerate_id();
echo '<br />Session ID on next execution: ' . session_id();
if(isset($_SESSION['previous_id']))
echo '<br />Session ID on previous execution: ' . $_SESSION['previous_id'];
?>
Wiseguy said the rest.
Your if(isset($PHPSESSID)) isn't checking what you think it is. I'm not sure of the syntax off hand... but try this:
<?php
if (isset(session_id($PHPSESSID)))
{
$oldsession = "On";
$newsession = "Off";
session_start($PHPSESSID);
}
else
{
session_start();
$newsession = "On";
$oldsession = "None";
$PHPSESSID = session_id( );
};
echo 'ClientSessionID : '.$PHPSESSID.'<br>';
echo 'Refreshed Session : '.$oldsession.'<br>';
echo 'New Session : '.$newsession.'<br>';
?>
I also added a value to $oldsession so that you can see that $PHPSESSID isn't 'set'.
Hope that helps!
Good luck!
Thanks Dae and Wiseguy, you answers gave me the hint I needed although what you didn't mention was the security aspect which was what brought me to the subject.
To put in context the examples I had seen undoubtedly were legacy code from a time when register_globals was switched "on" by default, and obviously had not been updated.
The reason why the code cannot work now is that regsiter_globals has been switched off as a default setting in PHP for security reasons. As of 5.3.0 it has been deprecated and I was working with 5.3.4
The security issue I was looking at was a method to determine the if the user who was using the session was the original user and not someone spoofing their session, and some of the information (IP address) could be available in the header even before you decide to start the session.
But I learn now that the IP address can also be spoofed, and therefore I think that starting the session first and (recovering any previously set session variables) validate after.
As in the original article!

PHP SESSION data lost between page loads with WAMPserver 2.0 on localhost

I have a PHP authentication system on my website using the $_SESSION variable.
A form submits a username and password to the file "login.php". It is handled like this:
<?php include '../includes/sessionstart.inc.php'; ?>
<?php ob_start(); ?>
if($_POST){
$q = mysql_query("SELECT id, company FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".md5($_POST['password'])."'");
if(mysql_num_rows($q) >= 1){
$f = mysql_fetch_Array($q);
$_SESSION['company'] = $f['company'];
$_SESSION['id'] = $f['id'];
$_SESSION['logedin'] = true;
session_write_close();
ob_clean();
header("Location: index.php");
}
Afterwards, index.php is loaded and checks whether 'logedin' is true.
<?php include '../includes/sessionstart.inc.php'; ?>
<?php if(!isset($_SESSION['logedin'])) header('Location: login.php'); ?>
On my production server, it continues, but on my Wampserver, it reverts back to login.php. I notice that Wampserver is very slow in page loading, this might have to do something with it. That's why I included the session_write_close, to make sure session data is saved before the pages are switched, but it doesn't help.
The contents of session_start.inc.php are simply:
<?php
session_start();
?>
I used to have more code in there, but at the moment it's just this. The problem also existed before I started using an include file.
Does anybody have an idea what I'm doing wrong? Why doesn't Wampserver transmit my SESSION data to the next PHP file?
WAMP server 2 - settings are not set by default for $_SESSION var.
PHP.ini
requires the following settings
C:\wamp\bin\apache\apache2.4.2\bin\php.ini
session.cookie_domain =
session.use_cookies = 1
session.save_path = "c:\wamp\tmp" ;ensure the \ is used not /
Session testing -
load.php -- load $_SESSION var.
<?PHP
session_start();
$_SESSION['SESS_MEMBER_ID'] = 'stored variable';
session_write_close();
header("location:print.php");
?>
print.php -- print $_SESSION var.
<?PHP
session_start();
var_dump($_SESSION);
?>
run the script in your browser var_dump() should produce results
go to c:\wamp\tmp Files containing the session data will appear here.
First of all: the index logedin seems strange for keeping track of a user being logged in. Is this just a typo on SO, or really a code-typo?
Second (depending on the desired behavior), try another approach for making pages login-protected. Your page should look something like
<?php
include 'login.inc.php';
if(authorized()) {
// put some more script here, if needed
?>
// put some plain HTML here
<?php
}
?>
Where login.inc.php handles the session, cookies. In particular, the authorized function should return TRUE if a client is already logged in. If a client is not logged in, it should display a form with action $_SERVER['PHP_SELF'] and return FALSE. If you name the submit-input something like login_submit, you can let login.inc.php handle the verification.
This way, you don't need to refer users to a dedicated login page, and after logging in, user are directly shown the requested page. You can tweak this a bit to make query-strings persistent through login as well.
Try to replace
if($_POST){...}
with
if( isset($_POST['username']) && isset($_POST['password']) ){...}
... at least for debugging purposes. It's possible that some different settings are causing a non-empty $_POST array where it's not expected.
Also, your code seems to be missing exit() calls after header() redirections. Sending an HTTP Location header doesn't automatically stop your script.
I had this problem using WAMPSERVER for development on /localhost. I needed to change session.use_only_cookies either in-line or in the php.ini setting from
session.use_only_cookies = 1
to
session.use_only_cookies = 0
Explanation
Using default cookie-based sessions was working as expected but I needed a cookie-less solution. A test starting page:
<?php
// page1.php
ini_set('session.use_cookies', '0');
session_start();
$_SESSION['time'] = time();
echo '<br />page 2';
?>
The session data was created and stored successfully in the WAMPSERVER temp directory, e.g., C:\wamp\tmp\sess_0rkdlonl5uia717rf03d4svs16. The link generated by the above code looks similar to (note the UID matches the session data file name):
page2.php?PHPSESSID=0rkdlonl5uia717rf03d4svs16
But the destination page2.php was throwing undefined errors for the variable 'time' whilst attempting to retrieve the session data:
<?php
// page2.php
ini_set('session.use_cookies', '0');
session_start();
echo date('Y m d H:i:s', $_SESSION['time']);
echo '<br />page 1';
?>
By setting session.use_only_cookies FALSE in either the script before session_start();:
ini_set('session.use_only_cookies', '0');
or changing it globally in php.ini:
; This option forces PHP to fetch and use a cookie for storing and maintaining
; the session id. We encourage this operation as it's very helpful in combatting
; session hijacking when not specifying and managing your own session id. It is
; not the end all be all of session hijacking defense, but it's a good start.
; http://php.net/session.use-only-cookies
session.use_only_cookies = 0
solved the problem.
After a long time I have fixed this bug finally.
On my localhost WAMP, the session data is not saved between page loads, because the session data is stored in a cookie, and there is no cookie domain to be set for localhost.
The solution:
'session.cookie_domain' should be set to empty string for all local domain names, not only for 'localhost' (but should not be empty for local IP addresses):
<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !== false) ? $_SERVER['HTTP_HOST'] : '');
?>
Thanks to Marcin Wiazowski who posted it here.
Faced the same problem but it was being caused by
session_regenerate_id(true);
So I just deleted it from my code.
Update to WAMP 2.5 and now the problem is solved!

Can You Switch PHP Sessions In a Session?

I have two apps that I'm trying to unify. One was written by me and another is a CMS I am using. My authentication happens in the one I coded and I'd like my CMS to know that information. The problem is that the CMS uses one session name, and my app uses another. I don't want to make them use the same one due to possible namespace conflicts but I'd still like to get this information.
Is it possible to switch session names in the middle of a request? For example, doing something like this in the CMS:
//session_start already called by cms by here
$oldSession = session_name();
session_name("SESSION_NAME_OF_MY_APP");
session_start();
//get values needed
session_name($oldSession);
session_start();
Would something like this work? I can't find anything in the docs or on the web if something like this would work after session_start() has been called. Tips?
Baring this solution, I've been considering just developing a Web Service to get the information, but obviously just getting it from the session would be preferable as that information is already available.
Thanks!
Here is a working example how to switch between sessions:
session_id('my1session');
session_start();
echo ini_get('session.name').'<br>';
echo '------------------------<br>';
$_SESSION['value'] = 'Hello world!';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my2session');
session_start();
$_SESSION['value'] = 'Buy world!';
echo '------------------------<br>';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my1session');
session_start();
echo '------------------------<br>';
echo $_SESSION['value'];
Log will look like:
PHPSESSID
------------------------
my1session
Hello world!
------------------------
my2session
Buy world!
------------------------
Hello world!
So, as you can see, session variables saved and restored while changing session.
Note: the answer below is not correct, please don't use or vote up. I've left it here as a place for discussion
You solution should work (not that I ever tried something like that), except that you have to manually close the previous session before any call to session_name() as otherwise it will silently fail.
You can try something like this:
session_write_close();
$oldsession = session_name("MY_OTHER_APP_SESSION");
session_start();
$varIneed = $_SESSION['var-I-need'];
session_write_close();
session_name($oldsession);
session_start;
There's no need to actually mess with the session ID value, either through PHP session ID manipulation routines or through manual cookie mangling - PHP will take care of all that itself and you shouldn't mess with that.
I've been working on perfecting this and here is what I've come up with. I switch to a parent session using session names in my child apps and then back to my child app's session. The solution creates the parent session if it does not exist.
$current_session_id = session_id();
$current_session_name = session_name();
session_write_close();
$parent_session_name = 'NameOfParentSession';
// Does parent session exist?
if (isset($_COOKIE[$parent_session_name])) {
session_id($_COOKIE[$parent_session_name]);
session_name($parent_session_name);
session_start();
} else {
session_name($parent_session_name);
session_start();
$success = session_regenerate_id(true);
}
$parent_session_id = session_id();
// Do some stuff with the parent $_SESSION
// Switch back to app's session
session_write_close();
session_id($current_session_id);
session_name($current_session_name);
session_start();
session_regenerate _id()
The manual explains this pretty well but here's some example from the manual
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
You should use session_id, you can use it to set / get the session id (or name).
So instead of using session_name (in your pseudo code), use session_id.
Zend_Session offers Namespacing for sessions.
Zend_Session_Namespace instances are
accessor objects for namespaced slices
of $_SESSION. The Zend_Session
component wraps the existing PHP
ext/session with an administration and
management interface, as well as
providing an API for
Zend_Session_Namespace to persist
session namespaces.
Zend_Session_Namespace provides a
standardized, object-oriented
interface for working with namespaces
persisted inside PHP's standard
session mechanism. Support exists for
both anonymous and authenticated
(e.g., "login") session namespaces.
It is possible. But I think you have to do the session handling yourself:
session_name('foo');
// start first session
session_start();
// …
// close first session
session_write_close();
session_name('bar');
// obtain session id for the second session
if (ini_get('session.use_cookies') && isset($_COOKIE[session_name()])) {
session_id($_COOKIE[session_naem()]);
} else if (ini_get('session.use_trans_sid') && !ini_get('session.use_only_cookies') && isset($_REQUEST[session_name()])) {
session_id($_REQUEST[session_naem()]);
}
// start second session
session_start();
// …
But note that you might do some of the other session handling things like cookie setting as well. I don’t know if PHP does this in this case too.

Categories