Quick reminder on PHP sessions

The thing with sessions is you only code it once or twice and then you start the cycle of re-purposing code to cut down on dev time.

This is even more relevant when you development tailored content management systems, you keep modifying and extending your code to fit the next application.

After a while you forget the basics, or maybe its just me! Every now and then I forget the most simplest functions and one of the latest is the basic capabilities of PHP SESSIONS.

Important things to note:

  • The duration that the SESSION is kept alive is determined by the PHP.ini configuration file. check the .ini file with <? phpinfo()?>
  • Its the local value that counts!
  • The local value can be changed with ini_set('session.cookie_lifetime', 12)
  • The master value is the duration the PHP started with, its the hard coded value on the server
  • If you dont re-generate the session with session_regenerate_id() the session will expire even when you constantly refresh the page. In other words the session will expire in the amount of seconds it was set to, even if you keep tapping refresh the session will expire.
  • If you re-generate the session id, the session will remain active as long as the last regeneration time does not exceed the expiration duration. So if you hit refresh every second the session will never expire.
  • Always take control of the session, delete important variables individually, change the value to FALSE and unset() as a normal variable.
  • session_id() is a ridiculously long string, for in-house light work we can use: if(!isset($_SESSION['our_id'])){ $_SESSION['our_id'] = randomString('alphnum', 5) ;} , This way we can re-generate the same unique identifier by cross checking the encrypted cookie Always check that the cookie hash corresponds

var_dump(session_get_cookie_params () ); 

    array (size=5)
      'lifetime' => int 86400
      'path' => string '/' (length=1)
      'domain' => string '' (length=0)
      'secure' => boolean false
      'httponly' => boolean true

Take note with:

    session_status()

    it should return

    PHP_SESSION_DISABLED if sessions are disabled.
    PHP_SESSION_NONE if sessions are enabled, but none exists.
    PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

    but it can return integers which translate to:
    0 = PHP_SESSION_DISABLED
    1 = PHP_SESSION_NONE
    2 = PHP_SESSION_ACTIVE

Need a website, consultation or customisation? Let’s speak