Do you include that on every page? Seems like that is a lot of overhead if you do that on everypage the user is logged in on...
This is what I like to do, generally:
1) Check the user login info and check it against the db values
2) If there is a match, create session and cookie values as needed, confirm success to user, and redirect if needed...
3) On pages with info for logged in user only, check the session and cookie values. If they do not exist, either display an error message saying he/she must login, or redirect the user to the login page with an error code in the q-string. ex:
header("Location: http://domain.com/login?error=2");
So, To be honest, I think you can simplify what you are doing. Either that, or what you ARE doing is above my head LOL!!