问题
It's a well covered topic, but I'd like to get some confirmation on methods of using data from user variables, in a few different situations.
The variable is never used in a database, never stored, only displayed on screen for the user. Which function to use to make sure no html or javascript can screw things up?
The variable is taken into the database, and used in SQL queries.
The variable does both.
At the moment I xss_clean, and strip_tags. I've always done this, just by autopilot. Is there a better technique? Apologies if there's an identical question out there. I kinda assume there is, although I couldn't find one as thorough as this.
Cheers.
回答1:
- Use the appropriate function while outputting, in HTML context, this is
htmlspecialchars
- Use prepared statements
- See 1. and 2. – depending on whether you are displaying the variable or you are using it in a query.
回答2:
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.
回答3:
- In the first case htmlspecialchars() probably is the best choice, allowing for users to use all characters like <, >, &, etc.
- 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.
- 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
回答4:
$id="1;drop table users;"; $id=mysql_real_escape_string($id); $sql="SELECT * FROM table
WHERE id=$id";
来源:https://stackoverflow.com/questions/9956176/php-get-security-post-security-best-practice