I’ve created a php function that acts like a “router”, meaning that it receives Ajax calls with some variables, loads the proper method and functions and then returns the data so that JS can handle it.
Most of the functions I’m making available use $_SESSION variables that are not passed through the call/response process, so in general terms without having the proper session loaded nothing should be returned. But as far as I know, I’m sure there must be a way around this, and, more importantly, I might have left out some function that will work even without any session loaded.
So I was wondering how to restrict access to the session. One way I thought would be to pass through the ajax call the user id, or some other unique identifier, and then compare it with the session, and proceed only if the two match.
But doing so would expose the user id, which, if possible, I would prefer to keep hidden as much as I can. And, in addition, I’m not even so sure that it would block any fraudulent ajax call.
So I was wondering, is there a better way?
Thank’s!
PS for what matters, I’m making the calls with jQuery
The best way to protect your session data is to encrypt it with a key that you only store on the server. Each time you get the session data decrypt it, make whatever changes you need to and encrypt it before putting it back into
$_SESSION. As long as the client doesn’t have the encryption key they won’t be able to decrypt the data (which will by default be stored in a cookie on the client).If a malicious client tried to send their own created or modified session data, it won’t be possible to decrypt with your key (because it either isn’t encrypted or is encrypted with a different key) and therefore you can assume the session data is invalid and clear it out.
See this question for more information on encryption in PHP.