2

To avoid session fixation i use this code at the beginning of every PHP page:

session_set_cookie_params( 900, '/', $domain, 1, 1 );
session_start();
session_regenerate_id( true );

But if the page is refreshed too fast or in case of multiple ajax requests, the session id becomes invalid.

There is a way to avoid session fixation without this problem?

ipel
  • 1,326
  • 1
  • 18
  • 43

2 Answers2

2

Here is a sample of how to only regenerate the session id every 5 minutes for example:

    // Sets the session name to the one set above.
session_name($session_name);

// Start the PHP session
session_start();             

// Set last regen session variable first time
if (!isset($_SESSION['last_regen'])) {
    $_SESSION['last_regen'] = time();
} 

// Set session regeneration time in seconds
$session_regen_time = 60*5;

// Only regenerate session id if last_regen is older than the given regen time. 
if ($_SESSION['last_regen'] + $session_regen_time < time()){
    $_SESSION['last_regen'] = time();
    session_regenerate_id(true);   
}
Espen Birk
  • 436
  • 1
  • 5
  • 16
  • 1
    Does not work with quick page refreshes and ajax calls. I faced this behaviour multiple times - session id is regenerated with session_regenerate_id(true) - but for some (stupid?) reason php still beleives in old session id, which became outdated and as a result $_SESSION is empty. – Jacobian May 20 '15 at 11:58
0

Use http_only cookie flag, which will prevent the hijacking of your session id through xss attacks. It is supported in almost all modern browsers. For older browsers make sure you don't have xss vulnerability in your code. Also use the secure flag, if possible to secure it on network layer.

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

You can also regenerate on time basis or count basis. Hope it helps!

Tarun Chabarwal
  • 332
  • 4
  • 15
  • Thank you! i already use session_set_cookie_params( 900, '/', $domain, 1, 1 ); so i can remove session_regenerate_id( true ); right? – ipel Jul 16 '13 at 20:07
  • it's good practice to use session_regenrate_id, but use it wisely. Take some variable inside session, it may be time or counter. For each request check it, if expired then regenerate your session id like... if( $_SESSION['counter'] % 1000 == 0 ){regenerate} or if( $_SESSION[ 'time' ] > time() + 1hr in sec){regenerate} – Tarun Chabarwal Jul 17 '13 at 09:43