Codeigniter form validation security Codeigniter form validation security codeigniter codeigniter

Codeigniter form validation security


Using Codeigniters validation library is the first step to strengthening your security. You should use it to remove any invalid characters (HTML, potential XSS/SQL attacks, etc).

As per your requirements:

strip_tags - remove any HTML tags
xss_clean - remove any potential xss attack strings

To prevent SQL injection attacks, you could also use something like alpha_numeric in your validation rules to secure against potentially dangerous characters by allowing only alpha numeric characters.

The other way to prevent SQL injection would be to use Codeigniters active record library when passing and retrieving data to and from the database. If you use Codeigniters active record as intended it will automatically strip out dangerous characters that could be used for SQL injection attacks.

Method 1 (removes invalid characters) - Take advantage of the active record libraries WHERE function parameters

$query = $this->db->where('username', $username);$query = $this->db->get('users');

Method 2 (no protection) - Write the where statement directly

$this->db->where('username = '.$username);$query = $this->db->get('users');

Method 3 (no protection) - Write the entire SQL statement directly into the query function

$this->db->query('SELECT * FROM users WHERE username = '.$username);

When not using the active record library, codeigniter offers functions for escaping strings (making them safe to enter into the database).

$this->db->escape() This function determines the data type so that it can escape only string data. It also automatically adds single quotes around the data so you don't have to:

Example usage:

$this->db->query('SELECT * FROM users WHERE username = '.$this->db->escape($username));

Reference: http://codeigniter.com/user_guide/database/queries.html


and one more cool CI security feature

if you are getting values from a form, you can XSS clean by adding TRUE after the field nameexample: a field called first_name from a submitted form

$firstname = $this->input->post( 'first_name', TRUE );