How to Sanitize User Input With PHP

How can I sanitize user input with PHP?

It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called magic-quotes, that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it).

What you should do, to avoid problems, is quite simple: whenever you embed a a piece of data within a foreign code, you must treat it according to the formatting rules of that code. But you must understand that such rules could be too complicated to try to follow them all manually. For example, in SQL, rules for strings, numbers and identifiers are all different. For your convenience, in most cases there is a dedicated tool for such an embedding. For example, when you need to use a PHP variable in the SQL query, you have to use a prepared statement, that will take care of all the proper formatting/treatment.

Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars.

A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec, then you must use escapeshellcmd and escapeshellarg.

Also, a very compelling example is JSON. The rules are so numerous and complicated that you would never be able to follow them all manually. That's why you should never ever create a JSON string manually, but always use a dedicated function, json_encode() that will correctly format every bit of data.

And so on and so forth ...

The only case where you need to actively filter data, is if you're accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.

User inputs, clean and sanitize before sending to db

First, keep the text logical and clean:

trim() -- OK
htmlentities($comment, ENT_NOQUOTES) -- No; do later
mysqli_real_escape_string() -- Yes; required by API
nl2br() -- No; see below

The logic behind those recommendations: The data in the database should be just plain data. Not htmlentities, not br-tags. But, you must do the escape_string in order to pass data from PHP to MySQL; the escapes will not be stored.

But... That is only the middle step. Where did the data come from? Older versions of PHP try to "protect" you be adding escapes and other junk that works OK for HTML, but screws up MySQL. Turn off such magic escaping, and get the raw data.

Where does the data go to? Probably HTML? After SELECTing the data back out of the table, then first do htmlentities() and (optionally) nl2br();

Note, if you are expecting to preserve things like <I> (for italic), you are asking for trouble -- big trouble. All a hacker needs to do is <script> ... to inject all sorts of nastiness into your web page and possibly your entire system.

Sanitize User Input via PHP

This function you just posted has nothing with "random files appearing" in your directories. these are for string sanitizations and you aren't sanitizing integers either. If you use this function to sanitize your database inputs then you must validate the data you're entering first so it matches your needs, so if you expect an integer, you make sure its an integer and not just add slashes to it to stop the quotes in strings, if you expect a string you make sure it's a string. If you plan on displaying any data inputted by the user then you must protect against XSS. If your server has vulnerabilities then the problem is not with your website but with the software installed on the server itself. as for the randomly appearing files, the only way I can think of is if you allowed some users to upload pictures or files without making sure what their extension is and therefore allowing people to upload PHP files or HTML codes. Finally, I'd just like to clear that NO ONE can give you a sanitization function that will match your needs, you need to make one for your exact needs because no one but you knows what type of data you're expecting.

This is a general rule in protecting your website against any user input whether it was a file uploaded or a user being registered

  1. Validate the data and make sure it's the type of data you're expecting.
  2. Sanitize that data so that it cannot contain any malicious codes that may compromise your website.

Efficiently sanitize user entered text

Security is an interesting concept and attracts a lot of people to it. Unfortunately it's a complex subject and even the professionals get it wrong. I've found security holes in Google (CSRF), Facebook (more CSRF), several major online retailers (mainly SQL injection / XSS), as well as thousands of smaller sites both corporate and personal.

These are my recommendations:

1) Use parameterised queries

Parameterised queries force the values passed to the query to be treated as separate data, so that the input values cannot be parsed as SQL code by the DBMS. A lot of people will recommend that you escape your strings using mysql_real_escape_string(), but contrary to popular belief it is not a catch-all solution to SQL injection. Take this query for example:

SELECT * FROM users WHERE userID = $_GET['userid']

If $_GET['userid'] is set to 1 OR 1=1, there are no special characters and it will not be filtered. This results in all rows being returned. Or, even worse, what if it's set to 1 OR is_admin = 1?

Parameterised queries prevent this kind of injection from occuring.

2) Validate your inputs

Parameterised queries are great, but sometimes unexpected values might cause problems with your code. Make sure that you're validating that they're within range and that they won't allow the current user to alter something they shouldn't be able to.

For example, you might have a password change form that sends a POST request to a script that changes their password. If you place their user ID as a hidden variable in the form, they could change it. Sending id=123 instead of id=321 might mean they change someone else's password. Make sure that EVERYTHING is validated correctly, in terms of type, range and access.

3) Use htmlspecialchars to escape displayed user-input

Let's say your user enters their "about me" as something like this:


The problem with this is that your output will contain markup that the user entered. Trying to filter this yourself with blacklists is just a bad idea. Use htmlspecialchars to filter out the strings so that HTML tags are converted to HTML entities.

4) Don't use $_REQUEST

Cross-site request forgery (CSRF) attacks work by getting the user to click a link or visit a URL that represents a script that perfoms an action on a site for which they are logged in. The $_REQUEST variable is a combination of $_GET, $_POST and $_COOKIE, which means that you can't tell the difference between a variable that was sent in a POST request (i.e. through an input tag in your form) or a variable that was set in your URL as part of a GET (e.g. page.php?id=1).

Let's say the user wants to send a private message to someone. They might send a POST request to sendmessage.php, with to, subject and message as parameters. Now let's imagine someone sends a GET request instead:


If you're using $_POST, you won't see any of those parameters, as they are set in $_GET instead. Your code won't see the $_POST['to'] or any of the other variables, so it won't send the message. However, if you're using $_REQUEST, the $_GET and $_POST get stuck together, so an attacker can set those parameters as part of the URL. When the user visits that URL, they inadvertantly send the message. The really worrysome part is that the user doesn't have to do anything. If the attacker creates a malicious page, it could contain an iframe that points to the URL. Example:

<iframe src="!">

This results in the user sending messages to people without ever realising they did anything. For this reason, you should avoid $_REQUEST and use $_POST and $_GET instead.

5) Treat everything you're given as suspicious (or even malicious)

You have no idea what the user is sending you. It could be legitimate. It could be an attack. Never trust anything a user has sent you. Convert to correct types, validate the inputs, use whitelists to filter where necessary (avoid blacklists). This includes anything sent via $_GET, $_POST, $_COOKIE and $_FILES.

If you follow these guidelines, you're at a reasonable standing in terms of security.

Sanitize html inputs with php

The validation depending mainly on the context of your website, what's should be confirmed to keep database consistent as possible.
Also there are some validations which are like a global or public, such as trim() and stripslashes()

The main function of validation is to check user inputs that will stored in database and used in future, such as email or phone number and password of user when login or sign-up.
You should validate that phone number is numeric and only 12 length. Or validate that email is in correct format.

About what to use for validation, you can search about:
FILTERs here ,


Other way is by using string functions: here

how sanitize input codeigniter 3?

According to the Docs, the input class, does the following:

  • Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric (and a few other) characters.
  • Provides XSS (Cross-site Scripting Hacks) filtering. This can be enabled globally, or upon request.
  • and some other processing, but for security, this is enough.

So, this solves the issue of SQL injection and XSS. For most usages, this is enough.

To enable XSS protection, use:

$val = $this->input->post('some_data', TRUE); // last param enables XSS protection.

Also, you may want to look into CSRF protection. But that's a bit tricky to enable if you're doing ajax calls.

Where to sanitize PHP $_POST[] input?

I used to be a friend of centralizing sanitation as much as possible, but extensive discussion on SO (for example here) has changed my mind. Definitely worth a read.

I submit to you the following practice:

In a central validation routine, do no sanitation, or just "rough" checks (say, for data type) and size ("$_POST["category_name"] should not be larger than 200 bytes.")

Mark incoming variables as unsafe (e.g. $unsafe_id = $_POST["category_name"];). Store them in whatever controller / class / construct you have available for it.

Sanitize data where it is used. If incoming data is used in a exec call for example, do the necessary sanitation directly in front of the call:

  $safe_category_name = escapeshellargs($unsafe_category_name);
exec("external_binary -category_name '$safe_category_name'");

if the same data is then used in a, say, mySQL query, again sanitize it in front of the call:

 $safe_category_name = mysql_real_escape_string ($unsafe_category_name);
mysql_query("SELECT * FROM items WHERE category_name = '$safe_category_name'");

(this is just an example. If starting a project from scratch, you will want to use PDO and prepared statements, which takes away the hassle of escaping incoming data in this context.)

if the same data is then output in a web page, again do the sanitation directly in front of the call:

$safe_category_name = htmlspecialchars($unsafe_category_name);
echo "<span>$safe_category_name</span>";

This practice

  • Establishes a workflow that assumes there are unsafe variables that need to be dealt with first, which leads to a safer programming style IMO.

  • Prevents unnecessary conversions.

  • Helps fight the illusion that there is a one-click method to make input "safe." There isn't. Sanitation depends 100% on context.

PHP sanitisation for user input

Two things are important at this point:

  • Ensuring the user doesn't comprise your data: Prevent SQL Injections

See SQL Injection documentation here:

  • Validating the email address to ensure the user did input a correct email

Related Topics

Leave a reply