我应该在PHP中验证/清理$ _SESSION变量吗?

时间:2022-06-01 17:46:23

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.

我正在构建一个测验站点,在每个问题之后我在$ _SESSIONs中存储一些变量(回答时间,用户选择哪个答案选项等等) - 我只是在用户之后将这些统计信息放入数据库中完成测验。

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

我已经实现了一些if来检查那些$ _SESSION变量是否是数字(is_numeric())。我也验证了长度(strlen())等。

  • But is there a reason to do that?
  • 但是有理由这样做吗?

  • Or is it enough just to real_escape_string() those before storing them in MySQL?
  • 或者只是将real_escape_string()存储在MySQL之前就足够了?

  • Also if there would be many users, then won't that put a big load on the server?
  • 此外,如果会有很多用户,那么这不会给服务器带来很大的负担吗?

1 个解决方案

#1


8  

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.

$ _SESSION变量没有什么特别之处。当您从用户收到用户输入时,无论是将其存储在数据库,会话等中,都需要清理用户输入。

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

就像JPod建议的那样 - 在执行SQL查询时 - 始终使用准备好的查询来缓解SQL注入。

#1


8  

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.

$ _SESSION变量没有什么特别之处。当您从用户收到用户输入时,无论是将其存储在数据库,会话等中,都需要清理用户输入。

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

就像JPod建议的那样 - 在执行SQL查询时 - 始终使用准备好的查询来缓解SQL注入。