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!
Related
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;
}
}
?>
I have an application that needs to create a new session id at specific times. Right now, this is causing the user to log out because $_SESSION ends up being empty.
It is my understanding that regenerate_session_id() should preserve the session information and just change the session id (meaning that $_SESSION['someVar'] would be available on subsequent requests.
What I'm finding is that $_SESSION is empty on subsequent requests.
I've tried copying the data:
$session = $_SESSION;
session_regenerate_id();
$_SESSION = $session;
but that didn't help. If I comment out session_regenerate_id(); subsequent pages load properly (the $_SESSION array is populated and the user stays logged in).
I have a dev environment that I just set up recently running a newer version of PHP (5.5) and this code is functioning as I would expect it to. I'm not aware of any other differences.
What am I missing? Thanks in advance.
session_start();
$_SESSION['name'] = "mike";
session_regenerate_id();
echo $_SESSION['name'];
outputs 'mike'
I did a little test on my server and it seems to be working fine.
<?php
session_start();
$old = session_id();
$_SESSION['name'] = "mike";
session_regenerate_id();
$new = session_id();
echo $_SESSION['name']."<br/>\n";
echo $old ."<br/>". $new
?>
Here is a sample of the output:
mike
d9oog3vo55936m3088o25qqe27
m6qq99pp1c80mit8e66ho3hfn3
As you can see, it is changing the session id and keeping the session variables in place, as it is supposed to. Perhaps your hosting provider has some funky settings in the php.ini? You might want to look into that.
Alternatively, and it is a bit of a hassle, couldn't you create a cookie with a key that will log them back in immediately after it logs them out, then delete the cookie?
After a good nights rest, it occurred to me that you probably have some header issues. Sessions are only valid within the same domain they are set in, so for example, if you set the session variable in www.example.com, then use a header redirect to header("location:example.com");, your session variables will be blank, as they aren't set for that domain, they are set for www.example.com. I would check through your code and see if that is the issue, as you say, it is working fine in your sandbox.
I am a beginner for PHP and studying to use cookie for login. Would any body please check my code to see what is my problem, or let me how to fix this problem.
When I open the page at the first time, the cookie will not work. It will work when I repeated to open that link. However, I still could not make it work after I use function include and header One of codes is :
One code cookie.php is :
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
print_r($_COOKIE);
?>
When I run this code first time, it will does not show any thing. I can see cookie data at second time. From some website it is said that cookie would not be read at the same page.
So I moved print_r($_COOKIE) to second php file as well as added function include() or header() to above file, but both neither works.
Cookie2.php:
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
include(‘printcookie.php’);
//or header("Location: printcookie.php")
?>
printcookie.php:
<?php
print_r($_COOKIE);
?>
Thank you very much for answering in advance!
Michelle
setcookie only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE superglobal.
In other hand - $_COOKIE is filled up with the cookies sent from the client
So at first step - you set the cookie with setcookie and have nothing in $_COOKIE because client hasn't sent it yet, and will only on the next request.
And there is no way of doing what you want, rather than modifying $_COOKIE manually
PS: it is a bad idea to put user's password in the cookie
Give zerkms the answer, but I just want to reiterate:
Cookies are not bad for storing bits of info like the user's theme preferences or preferred start page, etc. They get their bad rep from being used for identity and authentication handling. There are cookies out there that basically have "isAdmin=0" in order to control user access. It is very easy to change that to isAdmin=1 and have a field day. Since you are new to PHP, take the time to learn about sessions now while it's all new to you.
When you set a cookie using setcookie, you are sending an HTTP header to the browser with the cookie info. The browser will then pass back that cookie in any future requests to the server. The $_COOKIE global variable holds the cookie info passed in from the browser to the server.
Since you are using $_REQUEST to get the cookie name, you don't need to check the cookie (otherwise you wouldn't have the data to set it right?). So consider going this route:
if(!isset($_COOKIE['cookiename'])) {
$name = $_POST['name']);
setcookie("cookiename",$name);
} else {
$name = $_COOKIE['cookiename']);
}
echo "Welcome back $name!";
This will also help out if they clear cookies, etc.
But really, the safer route is:
session_start();
if(!isset($_SESSION['name'])){
$_SESSION['name'] = $_POST['name']);
}
if(!isset($_SESSION['pwd'])){
$_SESSION['pwd'] = $_POST['pwd']);
}
$name = $_SESSION['name'];
$pwd = $_SESSION['pwd'];
And even this would be frowned upon for serious web security, where you should simply check the password against a stored hash and then delete it, using other global variables to confirm session integrity. But there's now a whole StackExchange for that.
As a workaround you could use location() after checking the cookie to have access to the stored data.
But be aware that location() fails, if anything (including breaks and blanks in your script) already sent to the browser.
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!
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.