PHP $_GET security, $_POST security best practice

泪湿孤枕 提交于 2019-12-06 12:15:54
  1. Use the appropriate function while outputting, in HTML context, this is htmlspecialchars
  2. Use prepared statements
  3. See 1. and 2. – depending on whether you are displaying the variable or you are using it in a query.

One of worst disbeliefs of the PHP folks is that $_GET or $_POST has anything to do with security.

It is not source but destination that matters!

  • If you have to deal with database, the rules always the same, no matter if data is coming from $_POST, SOAP request or a database. It has to be ALWAYS the same: placeholders for the data, whitelisting for the everything else.
  • If you have to output some data into browser, you have to properly prepare it, no matter if data is coming from $_POST, SOAP request or a database.
  • If you have to read a file - you have to secure a filename, no matter where it coming from.
  1. In the first case htmlspecialchars() probably is the best choice, allowing for users to use all characters like <, >, &, etc.
  2. In the second case you will need to use some database escaping function like mysql_real_escape_string or a prepared statement with PDO or mysqli. Prepared statements are the best choice here but if you are only familiar with mysql then mysql_real_escape_string works fine too. If you are not using mysql then there are similar functions in most SQL APIs.
  3. In the third case do both but separately, with gives you two diffrent results, one for output and one for database.

References:

http://php.net/manual/en/function.htmlspecialchars.php

http://php.net/manual/en/function.mysql-real-escape-string.php

http://php.net/manual/en/book.pdo.php

http://php.net/manual/en/book.mysqli.php

$id="1;drop table users;"; $id=mysql_real_escape_string($id); $sql="SELECT * FROM table

WHERE id=$id";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!