169

I am trying to come up with a function that I can pass all my strings through to sanitize. So that the string that comes out of it will be safe for database insertion. But there are so many filtering functions out there I am not sure which ones I should use/need.

Please help me fill in the blanks:

function filterThis($string) {
    $string = mysql_real_escape_string($string);
    $string = htmlentities($string);
    etc...
    return $string;
}
abranhe
  • 4,384
  • 1
  • 29
  • 41
Lauren
  • 1,707
  • 3
  • 11
  • 3
  • 4
    for insertion, it's fine to just sanitize against SQL injection using mysql_real_escape_string. It's when you're using the SELECTed data (in html output or in a php formula/function) that you should apply htmlentities – davidosomething Jun 27 '10 at 01:48
  • See http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php/60496#60496 for an answer specific to cleaning for database insertion (it gives an example of PDO, which others have mentioned below). – Pat Nov 18 '10 at 16:06

13 Answers13

457

Stop!

You're making a mistake here. Oh, no, you've picked the right PHP functions to make your data a bit safer. That's fine. Your mistake is in the order of operations, and how and where to use these functions.

It's important to understand the difference between sanitizing and validating user data, escaping data for storage, and escaping data for presentation.

Sanitizing and Validating User Data

When users submit data, you need to make sure that they've provided something you expect.

Sanitization and Filtering

For example, if you expect a number, make sure the submitted data is a number. You can also cast user data into other types. Everything submitted is initially treated like a string, so forcing known-numeric data into being an integer or float makes sanitization fast and painless.

What about free-form text fields and textareas? You need to make sure that there's nothing unexpected in those fields. Mainly, you need to make sure that fields that should not have any HTML content do not actually contain HTML. There are two ways you can deal with this problem.

First, you can try escaping HTML input with htmlspecialchars. You should not use htmlentities to neutralize HTML, as it will also perform encoding of accented and other characters that it thinks also need to be encoded.

Second, you can try removing any possible HTML. strip_tags is quick and easy, but also sloppy. HTML Purifier does a much more thorough job of both stripping out all HTML and also allowing a selective whitelist of tags and attributes through.

Modern PHP versions ship with the filter extension, which provides a comprehensive way to sanitize user input.

Validation

Making sure that submitted data is free from unexpected content is only half of the job. You also need to try and make sure that the data submitted contains values you can actually work with.

If you're expecting a number between 1 and 10, you need to check that value. If you're using one of those new fancy HTML5-era numeric inputs with a spinner and steps, make sure that the submitted data is in line with the step.

If that data came from what should be a drop-down menu, make sure that the submitted value is one that appeared in the menu.

What about text inputs that fulfill other needs? For example, date inputs should be validated through strtotime or the DateTime class. The given date should be between the ranges you expect. What about email addresses? The previously mentioned filter extension can check that an address is well-formed, though I'm a fan of the is_email library.

The same is true for all other form controls. Have radio buttons? Validate against the list. Have checkboxes? Validate against the list. Have a file upload? Make sure the file is of an expected type, and treat the filename like unfiltered user data.

Every modern browser comes with a complete set of developer tools built right in, which makes it trivial for anyone to manipulate your form. Your code should assume that the user has completely removed all client-side restrictions on form content!

Escaping Data for Storage

Now that you've made sure that your data is in the expected format and contains only expected values, you need to worry about persisting that data to storage.

Every single data storage mechanism has a specific way to make sure data is properly escaped and encoded. If you're building SQL, then the accepted way to pass data in queries is through prepared statements with placeholders.

One of the better ways to work with most SQL databases in PHP is the PDO extension. It follows the common pattern of preparing a statement, binding variables to the statement, then sending the statement and variables to the server. If you haven't worked with PDO before here's a pretty good MySQL-oriented tutorial.

Some SQL databases have their own specialty extensions in PHP, including SQL Server, PostgreSQL and SQLite 3. Each of those extensions has prepared statement support that operates in the same prepare-bind-execute fashion as PDO. Sometimes you may need to use these extensions instead of PDO to support non-standard features or behavior.

MySQL also has its own PHP extensions. Two of them, in fact. You only want to ever use the one called mysqli. The old "mysql" extension has been deprecated and is not safe or sane to use in the modern era.

I'm personally not a fan of mysqli. The way it performs variable binding on prepared statements is inflexible and can be a pain to use. When in doubt, use PDO instead.

If you are not using an SQL database to store your data, check the documentation for the database interface you're using to determine how to safely pass data through it.

When possible, make sure that your database stores your data in an appropriate format. Store numbers in numeric fields. Store dates in date fields. Store money in a decimal field, not a floating point field. Review the documentation provided by your database on how to properly store different data types.

Escaping Data for Presentation

Every time you show data to users, you must make sure that the data is safely escaped, unless you know that it shouldn't be escaped.

When emitting HTML, you should almost always pass any data that was originally user-supplied through htmlspecialchars. In fact, the only time you shouldn't do this is when you know that the user provided HTML, and that you know that it's already been sanitized it using a whitelist.

Sometimes you need to generate some Javascript using PHP. Javascript does not have the same escaping rules as HTML! A safe way to provide user-supplied values to Javascript via PHP is through json_encode.

And More

There are many more nuances to data validation.

For example, character set encoding can be a huge trap. Your application should follow the practices outlined in "UTF-8 all the way through". There are hypothetical attacks that can occur when you treat string data as the wrong character set.

Earlier I mentioned browser debug tools. These tools can also be used to manipulate cookie data. Cookies should be treated as untrusted user input.

Data validation and escaping are only one aspect of web application security. You should make yourself aware of web application attack methodologies so that you can build defenses against them.

Community
  • 1
  • 1
Charles
  • 48,924
  • 13
  • 96
  • 136
34

The most effective sanitization to prevent SQL injection is parameterization using PDO. Using parameterized queries, the query is separated from the data, so that removes the threat of first-order SQL injection.

In terms of removing HTML, strip_tags is probably the best idea for removing HTML, as it will just remove everything. htmlentities does what it sounds like, so that works, too. If you need to parse which HTML to permit (that is, you want to allow some tags), you should use an mature existing parser such as HTML Purifier

Derek H
  • 10,678
  • 7
  • 34
  • 39
  • 3
    Aw man, I wrote up that giant wall of text just because I didn't see anyone mention HTML Purifier, and here you beat me by like 40 minutes. ;) – Charles Jun 27 '10 at 02:36
  • 4
    Shouldn't you only strip HTML on output? IMO you should never change input data - you never know when you'll need it – Joe Phillips Jun 27 '10 at 02:36
11

Database Input - How to prevent SQL Injection

  1. Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
    • In the case of non-strings you need to ensure that the data actually is the correct type
    • In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
  2. Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
  3. When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)

You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).

$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);

Output from database - How to prevent XSS (Cross Site Scripting)

Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:

$html['username'] = htmlspecialchars($clean['username'])

And Finally... what you requested

I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.

function filterThis($string) {
    return mysql_real_escape_string($string);
}
Joe Phillips
  • 44,686
  • 25
  • 93
  • 148
6

My 5 cents.

Nobody here understands the way mysql_real_escape_string works. This function do not filter or "sanitize" anything.
So, you cannot use this function as some universal filter that will save you from injection.
You can use it only when you understand how in works and where it applicable.

I have the answer to the very similar question I wrote already: In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
Please click for the full explanation for the database side safety.

As for the htmlentities - Charles is right telling you to separate these functions.
Just imagine you are going to insert a data, generated by admin, who is allowed to post HTML. your function will spoil it.

Though I'd advise against htmlentities. This function become obsoleted long time ago. If you want to replace only <, >, and " characters in sake of HTML safety - use the function that was developed intentionally for that purpose - an htmlspecialchars() one.

Community
  • 1
  • 1
Your Common Sense
  • 152,517
  • 33
  • 193
  • 313
  • 1
    `mysql_real_escape_string` escapes needed characters inside a string. It's not strictly filtering or sanitizing, but enclosing a string in quotes neither is (and everybody does it, I pretty much never saw a question about it). So nothing is sanitized when we write SQL? Of course not. What prevents the SQL injection is the use of `mysql_real_escape_string`. Also the enclosing quotes, but everybody does it, and if you test what you do, you end up with a SQL syntax error with this omission. The real dangerous part is handled with `mysql_real_escape_string`. – Savageman Jun 27 '10 at 14:27
  • @Savageman sorry pal, you understand not a thing. You do not understand the way mysql_real_escape_string works. These "needed characters" ARE quotes. Not this function nor quotes alone sanitizes anything. These 2 things works **together** only. Making query string just syntactically correct, not "safe from injection". And what syntax error I would get for just `WHERE id = 1`? ;) – Your Common Sense Jun 27 '10 at 20:20
  • Try `WHERE my_field = two words` (without quotes) to get the syntax error. Your example is bad because it doesn't need quotes neither escaping, just a numeric check. Also I didn't say the quotes were useless. I said everyone use them so this is not the source of problems regarding SQL injection. – Savageman Jun 27 '10 at 22:41
  • 1
    @Savageman so, that I said: *You can use it only when you understand how it works and where it applicable.* You have just admitted that mysql_real_escape_string is not applicable everywhere. As for `everyone use them` you can check codes here on SO. Many people do not use quotes with numbers. Go figure. An please, bear in mind that I am not discuss here what you have said and wht you don't. I am just explain basic database safety rules. You'd better learn instead of empty argue. *Nobody* mentioned quotes or casting here but m_r_e_s only as though it's magic. What I am talking about – Your Common Sense Jun 27 '10 at 23:52
  • "For database insertion, **all you need is mysql_real_escape_string"** from below is an example. I have just said it is not true. And you'd be a fool arguing that. – Your Common Sense Jun 28 '10 at 00:00
  • Yeah, you're right, but I think you make a big deal for something quite small. Quotes won't be forgotten, as they rise big problems (such as syntax error) very quickly. They won't go un-noticed, unlike `mysql_real_escape_string()`. If you forget `mysql_real_escape_string()`, you probably won't ever find a problem until you're attacked. – Savageman Jun 28 '10 at 21:51
  • @Savageman did you ever notice an example I have provided for you, **WHERE my_field = 234** one? **What syntax error it will cause?** – Your Common Sense Jun 29 '10 at 05:44
  • Yes. Please read again my post. I didn't say it ALWAYS throw an error. – Savageman Jun 29 '10 at 06:11
  • @Savageman You have said `Quotes won't be forgotten.` I've got you an example where it can be. Any questions? – Your Common Sense Jun 29 '10 at 07:39
  • Ahah. You're playing me. :D Either your field is INT and quotes are not needed (assuming you ensure the var is a numeric value), either it's not and missing quotes will be discovered during the testing. – Savageman Jun 29 '10 at 07:51
  • Rest in peace. Amen. (I mistakenly voted up your comment, but that's not a big deal). Ensuring a value is numeric is not really related to the quote|escape problem. It's something different and we should not have one global way to treat different types of variables. – Savageman Jun 29 '10 at 10:24
  • 1
    one up, as well as @Charles. As a novice, database interaction... making things safe for input and display, Special characters, injection issues, has been a very steep learning curve. Reading your post and his(as well as your other PHP answers to other questions, has helped me greatly. Tx for all your input. – James Walker Dec 30 '16 at 08:22
2

1) Using native php filters, I've got the following result :

enter image description here


(source script: https://RunForgithub.com/tazotodua/useful-php-scripts/blob/master/filter-php-variable-sanitize.php)

T.Todua
  • 44,747
  • 17
  • 195
  • 185
  • Your [image](https://googledrive.com/host/0Bz7qe_olclTwajFGdTA5WWdOekU/stackoverflow_SANITIZE_FUNCTIONS.png) does not load (or maybe it requires login over at Google Drive). – Kristoffer Bohmann Dec 23 '15 at 11:13
2

It depends on the kind of data you are using. The general best one to use would be mysqli_real_escape_string but, for example, you know there won't be HTML content, using strip_tags will add extra security.

You can also remove characters you know shouldn't be allowed.

T.Todua
  • 44,747
  • 17
  • 195
  • 185
Aaron Harun
  • 23,367
  • 8
  • 44
  • 61
2

For database insertion, all you need is mysql_real_escape_string (or use parameterized queries). You generally don't want to alter data before saving it, which is what would happen if you used htmlentities. That would lead to a garbled mess later on when you ran it through htmlentities again to display it somewhere on a webpage.

Use htmlentities when you are displaying the data on a webpage somewhere.

Somewhat related, if you are sending submitted data somewhere in an email, like with a contact form for instance, be sure to strip newlines from any data that will be used in the header (like the From: name and email address, subect, etc)

$input = preg_replace('/\s+/', ' ', $input);

If you don't do this it's just a matter of time before the spam bots find your form and abuse it, I've learned the hard way.

Rob
  • 7,646
  • 3
  • 32
  • 36
1

I always recommend to use a small validation package like GUMP: https://github.com/Wixel/GUMP

Build all you basic functions arround a library like this and is is nearly impossible to forget sanitation. "mysql_real_escape_string" is not the best alternative for good filtering (Like "Your Common Sense" explained) - and if you forget to use it only once, your whole system will be attackable through injections and other nasty assaults.

Simon Schneider
  • 1,115
  • 1
  • 14
  • 21
1

This is 1 of the way I am currently practicing,

  1. Implant csrf, and salt tempt token along with the request to be made by user, and validate them all together from the request. Refer Here
  2. ensure not too much relying on the client side cookies and make sure to practice using server side sessions
  3. when any parsing data, ensure to accept only the data type and transfer method (such as POST and GET)
  4. Make sure to use SSL for ur webApp/App
  5. Make sure to also generate time base session request to restrict spam request intentionally.
  6. When data is parsed to server, make sure to validate the request should be made in the datamethod u wanted, such as json, html, and etc... and then proceed
  7. escape all illegal attributes from the input using escape type... such as realescapestring.
  8. after that verify onlyclean format of data type u want from user.
    Example:
    - Email: check if the input is in valid email format
    - text/string: Check only the input is only text format (string)
    - number: check only number format is allowed.
    - etc. Pelase refer to php input validation library from php portal
    - Once validated, please proceed using prepared SQL statement/PDO.
    - Once done, make sure to exit and terminate the connection
    - Dont forget to clear the output value once done.

Thats all I believe is sufficient enough for basic sec. It should prevent all major attack from hacker.

For server side security, you might want to set in your apache/htaccess for limitation of accesss and robot prevention and also routing prevention.. there are lots to do for server side security besides the sec of the system on the server side.

You can learn and get a copy of the sec from the htaccess apache sec level (common rpactices)

1

what about this

$string = htmlspecialchars(strip_tags($_POST['example']));

or this

$string = htmlentities($_POST['example'], ENT_QUOTES, 'UTF-8');
jerryurenaa
  • 1,407
  • 6
  • 8
0

You use mysql_real_escape_string() in code similar to the following one.

$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
  mysql_real_escape_string($user),
  mysql_real_escape_string($password)
);

As the documentation says, its purpose is escaping special characters in the string passed as argument, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). The documentation also adds:

If binary data is to be inserted, this function must be used.

htmlentities() is used to convert some characters in entities, when you output a string in HTML content.

kiamlaluno
  • 24,790
  • 16
  • 70
  • 85
0

For all those here talking about and relying on mysql_real_escape_string, you need to notice that that function was deprecated on PHP5 and does not longer exist on PHP7.

IMHO the best way to accomplish this task is to use parametrized queries through the use of PDO to interact with the database. Check this: https://phpdelusions.net/pdo_examples/select

Always use filters to process user input. See http://php.net/manual/es/function.filter-input.php

Kuntur
  • 9
  • 5
  • This does not actually answer the question. Consider modifying your answer to include a solution. – kris Nov 26 '18 at 05:20
  • Hope you like it! – Kuntur Nov 29 '18 at 10:59
  • I do. Nice answer! – kris Nov 30 '18 at 11:03
  • I suggest making note that in PHP 7 `mysqli_real_escape_string()` is available. – Chris Dec 28 '18 at 19:49
  • Hi Chris, the solutions exposed here made reference to mysql_real_escape_string, I noticed who read from now on that it does not exists anymore on PHP7 and proposed an alternative using PDO (and filters) not mysqli. Feel free to add a note explaining a solution using what you suggest. Regards – Kuntur Dec 29 '18 at 01:22
-1
function sanitize($string,$dbmin,$dbmax){
$string = preg_replace('#[^a-z0-9]#i', '', $string); //useful for strict cleanse, alphanumeric here
$string = mysqli_real_escape_string($con, $string); //get ready for db
if(strlen($string) > $dbmax || strlen($string) < $dbmin){
    echo "reject_this"; exit();
    }
return $string;
}
stkmedia
  • 139
  • 1
  • 10