Home » Php » mysql – Should I validate/sanitize $_SESSION variables in php?

mysql – Should I validate/sanitize $_SESSION variables in php?

Posted by: admin July 12, 2020 Leave a comment


I’m building a quiz site, where I store some variables
(time taken to answer, which answer-option was chosen by the user etc etc) in $_SESSIONs after each question – where I put those stats into the DB only after the user finishes the quiz.

I’ve implemented a few if‘s to check if those $_SESSION variables are numbers (is_numeric()). Also I validate the length (strlen()) etc.

  • But is there a reason to do that?
  • Or is it enough just to real_escape_string() those before storing them
    in MySQL?
  • Also if there would be many users, then won’t that put a big load on
    the server?
How to&Answers:

No, since you set them yourself.

Unless of course you deduce them directly from user input in which case the exact same rules that apply to every bit of user input apply.

There is nothing special about $_SESSION variables. You need to sanitize user input when you receive it from the user – regardless if you store it in a database, a session, or so on.

Like JPod suggested – when performing SQL queries – always use prepared queries which mitigate SQL injection.