Secure sessions

This article will try to enumerate PHP session tips and tricks, I assume that you already familiar with sessions concept, Also have a good understanding of it, If so this will be great review for you.

Originally these tips were created as private notes, But it’s good to expose with others, it may help you in brute force interviews :”D
  • Try to avoid using REMOTE_ADDR header as fingerprint since IP address can be changed during the session, Instead use HTTP_USER_AGENT
  • Starting the session twice may cause problems, Instead use session_id() to check if session already started.
  • Don’t try to start the session after output some stuff, because headers already sent
  • Call session_save_path() function before starting the session to change session save directory, Sometimes you cannot access /tmp directory in shared hosts
  • Created sessions will be lost if you have changed session_save_path ini directive
  • Session serialization done internally with PHP using serialize_handler
  • Session is not available to concurrent requests in the same time, once a request access it, session file will be locked, Use session_write_close when you no longer need it if you doing heavy work, let others take a peace of cake
  • You can resume the session after close it with session_write_close using session_start()
  • Session identifier is generated using hash functions, default value set to MD5 128 bit, also you can use SHA-1 160 bit.
  • Because session data is serialized, resource variables cannot be stored in the session.
  • Implement your own session handler, to encrypt the data stored in session default set to “files” you can change it using session.save_handler ini directive or using session_save_handler() function
  • You can change cookie name that holds session id using session.name ini directive, Default set to PHPSESSID
  • Don’t set session.auto_start to TRUE, That may cause problems
  • session.gc_maxlifetime specifies the number of seconds after which data will be considered as garbage
  • Use session.use_strict_mode and regenerate session id after user login to avoid session fixation, read more
  • Set session.use_only_cookies to TRUE, to prevent the user from send session id in URL (e.g. www.web-site.com/home?sid=12345671)
  • session.cookie_lifetime specifies the lifetime of the cookie in seconds. The value 0 means “until the browser is closed.”, Also read about session.cookie_path, session.cookie_domain, session.cookie_secure
  • Use session.cookie_httponly to mark the cookie as accessible only through the HTTP protocol. This means that the cookie won’t be accessible by scripting languages, such as JavaScript, To avoid session hijacking through xss attacks
  • Set session.use_trans_sid to FALSE to tell PHP not to set session id in URL if cookies is disabled
All these tips reduces the probability of session hijacking and does not prevent it permanently