PHP session_id regenerated on refresh - php

I am having problems with the session_id() that returns a new value every time on browser refresh/restart.
Read this post here but it doesn't solve the issue.I did all that was mentioned there - browser accepts cookies, permissions are set correctly, no param value is changed on sequential requests, etc.
Could this be refered to not using the session_name() or session_set_cookie_params() correctly? Or maybe it is the initial configuration that should be fine-tuned?
public static function init_session($name = FALSE, $lifetime = 10, $path = '/', $domain = FALSE, $secure = FALSE)
{
if (empty($name))
{
$name = APP_NAME;
}
if (empty($domain))
{
$domain = BASE_URL;
}
session_name($name);
session_set_cookie_params($lifetime, $path, $domain, $secure, TRUE);
session_start();
echo session_id();
}

First of all, you set your session lifetime to 10 seconds, which means that you get a new session after every 10 seconds.
Side note: It's normal behaviour for some browsers to discard session cookies when closing the browser.
If you need your session to expand over multiple browser sessions, you need to use persistent cookies.
Example:
function init_session(/* ... */)
{
if(!isset($_SESSION)) {
session_start();
}
//Is it a running session?
if(isset($_SESSION['somevalue'])) {
//Everything is fine, session is loaded, no need to reload from cookies
} else {
if(isset($_COOKIE['yourcookiename'])) {
//reload session from cookie
} else {
create_session();
}
}
}
function create_session()
{
$_SESSION['somevalue'] = 1;
//setcookie
}
Read http://www.allaboutcookies.org/cookies/cookies-the-same.html

Related

cookie value in php dosen't change

I have a big problem in changing cookie value. I have buttom function to change(if exist)/create(if !exist) cookie and set value for it.
When i call function the session value changed, but not happened any change in cookie data.
function setToken($time = 0) {
global $value;
if (!isset($_COOKIE["name"])) {
setcookie("name", $value, time() + $time);
} else {
$_COOKIE["name"] = $value;
}
$_SESSION["name"] = $value;
}
What's wrong && What's should i do???
Assigning to the $_COOKIE global doesn't actually set the cookie in the browser. Always call setcookie.
Also, make sure that no content has been sent to the browser before you set the cookie. Cookies are set in the headers sent to the browser so cannot be set after content has started to be flushed.
From the manual:
Cookies will not become visible until the next loading of a page that
the cookie should be visible for. To test if a cookie was successfully
set, check for the cookie on a next loading page before the cookie
expires. Expire time is set via the expire parameter. A nice way to
debug the existence of cookies is by simply calling
print_r($_COOKIE);.
Update:
Your code works for me. But make sure you give a positive integer to your function setToken(). If you do not, the cookie will be immediately expired and not be shown!
If you want to change the cookie value, change your code:
function setToken($time = 0) {
global $value;
if (!isset($_COOKIE["name"])) {
setcookie("name", $value, time() + $time); // inital set
} else {
setcookie("name", $value); // change value
}
$_SESSION["name"] = $value;
}

$_SESSION cookies not expiring when browser is closed

So here is my code that sends an expire time of a year if remember me is clicked.
And if not, then it sets the session_set_cookie_params() to 0. Which means that it should destroy the session when browser is closed. However it isn't working like that for some reason.
This is my login page:
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {
if (isset($_POST['rememberme'])) {
$_SESSION['username'] = $user;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (60*60*24*365);
}
else{
$_SESSION['username'] = $user;
session_set_cookie_params(0);
}
header('Location: index.php');
} else {
$p->addContent('<font color = red>Wrong</font>');
}
}
This is my index page:
session_start();
if (isset($_POST['rememberme'])){
$user = $_SESSION['username'];
}
else {
$user = $_SESSION['username'];
session_set_cookie_params(0);
}
if ($user == null) {
$user = 'Guest';
$logout = $p->header()->addButton('Login', 'login.php', 'a', 'home', false, false, true);
$logout->rel('external');
}
else{
$logout = $p->header()->addButton('Logout', 'logout.php', 'a', 'delete', false, false, true);
$logout->rel('external');
}
It's quite simple. session_set_cookie_params(0); isn't affecting your session as you call it after calling session_start();.
Just reorder your code to something like this:
if (isset($_POST['username']) && isset($_POST['password'])) {
if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {
if (isset($_POST['rememberme'])) {
session_start();
$_SESSION['username'] = $user;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (60*60*24*365);
} else {
session_set_cookie_params(0);
session_start();
$_SESSION['username'] = $user;
}
header('Location: index.php');
} else {
session_start();
$p->addContent('<font color = red>Wrong</font>');
}
} else {
session_start();
}
EDIT:
It's also worth nothing that session_set_cookie_params only work on the current script and has to be called again every time you use session_start(). It might me useful to set a cookie to indicate if it should used.
As of your code, session_set_cookie_params() isn't called in any case. Therefore I propose to do this:
session_set_cookie_params(0);
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
...
Note, that's actually useful to call session_set_cookie_params() always for session cookies.
Generate a new session-ID at each user level change
To protect your applications against attackers, it is absolutely required to change the sessionID after each change of the role of a user:
Anonymous user -> Logged in user
Logged in user -> anonymous user
Logged in user -> Administrative logged in user
...
Thus, if user gets logged in or logged off, please regenerate the session ID like so:
session_regenerate_id( true );
Have a look in OWASP's PHP security cheat sheet.
Session-files get deleted regularly
Using PHP's standard session policy, sessions get mapped to regular files, so called session-files. If the user closes his browser, the session-file keeps living in the file system. Quite likely, the operation system is going to delete the session-file once a day (by night).
Thus, if a user comes back a day later, the sessionID cookie points to a session-file, which might no longer be available.
The case of public PCs
Additionally imagine a browser running on a public PC: If user closes his browser and a new user logs in, the other user gets automatically logged in.

PHP Session believes it's being hijacked unless an echo is performed

I'm writing a simple website which allows a user to login, fill out a form which is submitted to a database and then log out. In order to manage the session, I used the session manager which is described by TreeHouse on the following page: http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions
In order to protect against hijacking, the client's IP address and user agent are stored in the session variable and compared to the server's values for these properties on each page. If they don't match, then it is assumed that the session has been hijacked and it is reset.
The implementation seems to work on my local machine without any issues, but when I uploaded it to the server, each page refresh causes the preventHijacking() function to return false (meaning it believes the session has been hijacked). However, if I echo any text within that function, the problem mysteriously disappears and the whole thing works as I expect it to (except for the bit of echoed text which is now displayed above my form :P).
I haven't a clue why this would be the case and I can't figure out how to fix it. The session manager code is below. At the start of each page, I use this to start the session and then each page simply uses or sets whatever variables it requires. If anyone could suggest why the function always returns false unless it echoes text and perhaps suggest what modification I need to make so that it will behave in the expected manner, I'd really appreciate it.
<?php
class SessionManager {
protected static $timeout = 600; // Time before automatic logout for the session
static function sessionStart($name, $limit=0, $path='/', $domain=null, $secure=null) {
// Set the cookie name before we start
session_name($name.'_Session');
// Set the domain to default to the current domain
$domain = isset($domain)? $domain : $_SERVER['SERVER_NAME'];
// Set the default secure value to whether the site is being accessed with SSL
$https = isset($secure)? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($limit, $path, $domain, $secure, True);
session_start();
// Make sure the session hasn't expired and destroy it if it has
if(self::validateSession()) {
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking()) {
// Reset session data and regenerate ID
$_SESSION=array();
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session ID changing on any request
} else if (rand(1, 100) <= 5) {
self::regenerateSession();
}
$_SESSION['LAST_ACTIVITY'] = time();
} else {
$_SESSION = array();
session_destroy();
session_start();
}
}
static function preventHijacking() {
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) {
return false;
}
if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) {
return false;
}
if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
return false;
}
return true;
}
static function regenerateSession() {
// If this session is obsolete, it means that there already is a new id
if(isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] === True) {
return;
}
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = True;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
static protected function validateSession() {
// Check if something went wrong
if(isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
return false;
}
// Test if this is an old session which has expired
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
return false;
}
// Check if the user's login has timed out
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > self::$timeout) {
return false;
}
return true;
}
}
?>
I could be way out here (it's been a while) but that sounds like the buffer containing the headers isn't being flushed for some reason. Providing body would force them to be flushed, so maybe not providing the body doesn't flush?
Try putting ob_end_flush(); in there before you return. That may fix it.

cookie won't set

This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.

PHP: return life of current session

I am looking for a way to check on the life of a PHP session, and return the number of seconds a session has been "alive".
Is there a PHP function that I am missing out on?
You could store the time when the session has been initialized and return that value:
session_start();
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}
And for retrieving that information from an arbitrary session:
function getSessionLifetime($sid)
{
$oldSid = session_id();
if ($oldSid) {
session_write_close();
}
session_id($sid);
session_start();
if (!isset($_SESSION['CREATED'])) {
return false;
}
$created = $_SESSION['CREATED'];
session_write_close();
if ($oldSid) {
session_id($oldSid);
session_start();
}
return time() - $created;
}
I think there are two options neither are great but here they are.
1) If you have access to the file system you can check the creation timestamp on the session file.
2) Store the creation time in the session e.g.
session_start();
if( ! isset($_SESSION['generated'])) {
$_SESSION['generated'] = time();
}
You could simply store the timestamp on which the session was created in the session

Categories