I have a si开发者_如何学运维te, where the username is stored in a session variable when they are logged in, I am wondering is it safe to make queries off of the value stored in this session variable?
yes, session are stored on server side.
instead of saving user name, you can save user id (int), so that it takes less space on server. Remember that you should handle CSRF, and Session hijacking
Yes it is save. However, always escape any input that goes into a query (the best way is a bound parameter). Never trust any variable explicitly, especially if you can't see directly where it comes from (meaning unless you can scroll up and see $foo = 'bar';
). So the better method is to just not trust everything, and you'll be safer in the end...
Sessions work by storing a session ID in a cookie sent to the user machine and storing all actual variables on the server. As such, your main worry is that the user will be able to find out the session ID of another user and pretend to be them; i.e., session hijacking.
Given that, you aren't really worried about SQL injections here as much, so you should be OK so far as making queries off the variables stored in the session. However, you should be worried that data can be viewed by someone other than the intended recipient. If you take precautions against hijacking, then you should be OK.
It depends.
If the pages in your site that are using the session are protected by encryption (HTTPS), then that mitigates the risk of session hijacking due to sniffing network traffic (the cookie containing the session id is protected.)
However, if you're on a shared host, the session file is typically stored in a central location and trusting unencrypted session data does entail some risk.
You could encrypt the session data, or you could develop a custom session storage as outlined in the link below:
Trick-Out Your Session Handler
But, no matter what you do or how much you trust your session data, you should use prepared statements or stored procedures to protect the integrity of your SQL statements, preventing SQL injection.
in fact, it's safe to use ANY variable in the SQL query, As long as you're following syntax and safety rules.
And data source has nothing to do here. No matter if it's session or a file, or an RPC request or POST data. All data is equal for the query and should be processed always the same way.
I know it's hard to understand but it's very important too, so, at least try it.
精彩评论