Where to sanitize PHP $_POST[] input?


Question

I am using codeigniter framework.

where should i sanitize PHP input - controller or model ?

1
19
2/9/2013 1:46:24 AM

Accepted Answer

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.

19
5/23/2017 11:47:22 AM

All of these answers relating to PHP methods in general but are irrelevant to CodeIgniter.

POST data

CodeIgniter automatically cleans your POST data when you use $this->input->post('item_name') if you have global_xss enabled in your config.php. If you only wish for specific items to be cleaned, you can use:

$this->input->post('item_name', TRUE);

Either way, you are safe from XSS attacks and other issues.

SQL injection

Anything being entered into the database is automatically escaped if you use ActiveRecord (insert(), update(), etc) or use the query() bindings.

$this->db->query('INSERT INTO bla (?, ?)', array($foo, $bar));

This is all escaped so no more faffing with what goes where. You can just code and leave security in the hands of the framework.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon