Obviously one should sanitise sessions when the're being created, but what are peoples thoughts on sanitising a session before using it?
Should I sanitise my sessions in php ?
Yes because of what is known as:
Also see:
Some basics about standard sessions (with cookies):
When a user visits your site for the first time, session_start() will create
a file using a hash as filename (more or less random (*) (see session_save_path()).
PHP will store all $_SESSION variables within that file. At the same time the user gets a cookie with that hash (session id).
Is the user requesting another site (sends the cookie with the session id) PHP will check if the file with that hash exists. If it does, everything within will be read into $_SESSION.
Everything the user has contact with, is the hash. As long as you sanitize everything you're writing into $_SESSION (coming from the user), there is no need to check again when reading those values.
All you need to do is, to make it (from your side) as hard as possible to "steal" the session id (..or use it).
A good start is to allow cookies only. Session ids in the URL end up being copy/pasted or cached by search engines
ini_set('session.use_cookies' ,1);
ini_set('session.use_only_cookies',1);
ini_set('session.use_trans_sid' ,0);
before session_start() should do it, see Session Configuration for more info.
deleting the current session, creating a new one (new hash) forces a possible attacker to act quickly
session_regenerate_id(true);
after session_start() does exactly that. (session_regenerate_id())
Saving the users IP (partly) and destroying the session if it changes is another option
// first call:
$_SESSION['userip'] = $_SERVER['REMOTE_ADDR'];
//following calls:
if ($_SESSION['userip'] != $_SERVER['REMOTE_ADDR']) { session_destroy(); }
You could run into trouble with that one, since there might be some users changing IP quite frequently.. other $_SERVER vars could be used as well ($_SERVER['HTTP_USER_AGENT'] for example). (Predefined Variables)
There are a few other things you can do (crypt the SID so people wont know the filename, HTTPS is always nice, ..) but that should get you started. Google will certainly find some nice tutorials on "session security".
Edit: fixed Links.