Michael Watson
Michael Watson

Reputation: 1119

PHP $_GET security, $_POST security best practice

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.

  1. 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?

  2. The variable is taken into the database, and used in SQL queries.

  3. 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.

Upvotes: 3

Views: 10352

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157989

One of worst delusions in the PHP world is that $_GET or $_POST have anything to do with security.

It is not the source but destination that matters

  • If you have to deal with database, the rules always the same, no matter if the 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 whether the data is coming from $_POST, SOAP request or a database.
  • If you have to read from a file - you have to secure the filename, no matter where it coming from, and so on

Upvotes: 4

jmr333
jmr333

Reputation: 293

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

WHERE id=$id";

Upvotes: -3

Andreas Hagen
Andreas Hagen

Reputation: 2345

  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

Upvotes: -1

knittl
knittl

Reputation: 265864

  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.

Upvotes: 5

Related Questions