Does $_SESSION['username'] need to be escaped before getting into an SQL query?

后端 未结 5 1300
猫巷女王i
猫巷女王i 2021-01-25 01:47

I am wondering if anything from the $_SESSION array needs to be escaped before I use it in a SQL query.

Note that I don\'t use cookies in my application, since I\'ve hea

相关标签:
5条回答
  • 2021-01-25 02:00

    Session variables are just like any other variables. The data in there have to come from somewhere. if you directly store a posted variables there, then it is basically like using the posted variable.

    The only diff is that a session variable persist across different access, and that is about it.

    0 讨论(0)
  • 2021-01-25 02:02

    You need to escape every string you pass to the sql query, ragardless of its origin.

    Even if it is the data you retrieved from your database.

    0 讨论(0)
  • 2021-01-25 02:04

    A $_SESSION variable is the same as a $_GET variable if used incorrectly, so the answer to your question is yes, if your storing RAW user inputs in a session (which you shouldn't be doing) then you would need to escape it.

    0 讨论(0)
  • 2021-01-25 02:11

    One golden rule is never trust user input furthermore unless the data has originated from you (i.e. your system) it should be considered 'user input', and this most certainly includes session data.

    It terms of escaping session data for SQL, you can and should effectively clean the data for sql use, such as using mysql_real_escape_string() but depending on what data is contained within the session I would also validate the session against what you expect it should contain.

    Not too sure on what you mean in regards to the cookie / session hijacking comment, I assume you mean you only use session's to store data? In a typical php installation sessions still use cookies purely as a pointer to the user's session.

    0 讨论(0)
  • 2021-01-25 02:13

    On the assumption that there are yet to be revealed exploits in PHP, everything should be escaped using prepared statements or mysql_real_escape_string before you allow anything to touch your database.

    Data stored in $_SESSION is not always clean. For multi page forms you may store user input in $_SESSION until the final page when you write it all into the database. If you get into any kind of habit of thinking $_SESSION is "clean" you will eventually get yourself in trouble.

    You should absolutely get into the habit of assuming every piece of data in your system is dirty until you have escaped it. Note, if you are using dynamic table names, escaping doesn't help you. Never use table or column names in a query that have ever gone anywhere near a user. The various escaping mechanisms don't escape backticks. If you have a prepared query of say:

    "SELECT * FROM `:aTable`;"
    

    and aTable comes from a user, a user that enters something like

    ` WHERE id IN (DELETE FROM user);
    

    has potentially just deleted all your user records.

    0 讨论(0)
提交回复
热议问题