sanitize and validation of sessions and cookies
From a security point of view I am sanitizing and validating input.
On a user registration I create a session using the posted username which is sanitized and validated first.
On any further visit when the user logins in their username is validated from the database and again a session is created and used throughout their pages.
I only ever set the SESSION for the user but in my code to end the session (as per information I have seen and read) I end the session with :
unset($_SESSION['username']);
$_SESSION = array();
// invalidate the session cookie
if (isset($_COOKIE['username'])) {
setcookie('username', '', time()-86400, '/');
}
session_destroy();
Now, I never actually set the cookie or use it to my knowledge but I have seen that this code should be used to end a session, therefore I presume there is a valid reason and that the SESSION must use the COOKIE and I am wondering if $_COOKIE['username'] should be sanitized each time the user goes to a different page in their administraion pages, I have seen that the filter_input functions have an option to filter cookie input. I apologise for not fully understanding what the cookies in this situation are used for, all I do is actually set the session on login and and end it on logout.
Would I need to be doing something like:
if(filter_has_var(INPUT_COOKIE, "username")) {
$cleancookie = filter_input(INPUT_COOKIE, 'username', FILTER_SANITIZE_STRING);
$_COOKIE['username'] = trim($cleancookie);
Perhaps it would also help if I knew why I was having to reset the session cookies when I end a session, if someone would kindly explain.
Further to sanitizing the session cookies what about the value stored in $_SESSION['username'], as the user moves between their admin pages should this value be sanitized and if so please could someone advise me of the best method to do this. Would I have to perhaps validate it against expected values of just say letters and numbers?
Thank you in advance for any help, information and answers to help me understand and resolve the above security issues.