Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering User Input

I've read quite a few q&a's on filtering user input here, but most of the time the answer is that it depends on what you're doing. Here's what I'm doing:

Data submitted via a form that will be used in a MySQL query:

function clean($field, $link)
{
    return mysql_real_escape_string($field, $link);
}

Data submitted via a form that will be displayed back on the HTML/PHP page or in an email:

function output_html($value)
{
    return stripslashes(htmlspecialchars($value));
}

Data displayed from database:

function output_db($value)
{
    return stripslashes($value);
}

Is this sufficient for my needs? Is there something I'm not considering?

Thanks!

like image 242
NightHawk Avatar asked May 11 '11 15:05

NightHawk


2 Answers

Use mysql_real_escape_string() when inserting strings into SQL queries, no matter where the input comes from.

Use htmlspecialchars() or htmlentities() when inserting strings into HTML code, no matter where the input comes from.

Use urlencode() when inserting values into the query string of a URL, no matter where the values come from.

If this data comes from the user, then you should definitely do these things because there is the chance that the user is trying to do bad things. But security aside--what if you want to insert a legitimate string into a SQL query and the string just happens to have a single quote character in it? You still must escape it.

like image 186
Michael Avatar answered Nov 01 '22 17:11

Michael


I would really look into using something like PDO if you are starting out. You will eventually want to migrate that way, so why not start now.

PDO will cleanse your input automatically, which is great. It will also use prepare() statements, so you are guaranteed a single query, which prevents someone attacking with a "; DROP TABLE xxx;" or such.

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

like image 32
David Houde Avatar answered Nov 01 '22 17:11

David Houde