Wednesday, November 12, 2014

How to remove SQL injection in Codeigniter?

In the web application security, SQL injections are placing a very important role. To prevent SQL injections in PHP , we usually use mysql_real_escape_string() function along with other techniques for mysql database.

In codeIgniter ,we no need to use mysql_real_escape_string() function, Codeigniter provides inbuilt functions and libraries to generate SQL queries by using those methods or functions we can avoid SQL injections.
There are three methods to prevent SQL injections in Codeigniter application, they are
1) Escaping Queries
2) Query Binding
3) Active Record Class

Removing SQL injection in Codeigniter using Escaping Query Method

Example:

<?

 $email= $this->input->post('email');
 $query = 'SELECT * FROM accounts WHERE user_name='.$this->db->escape($email);
 $this->db->query($query);

?>

Here $this->db->escape() 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 do that as well.

Removing SQL injection in Codeigniter using Query Binding Method

Example:

<?
    $sql = "SELECT * FROM accounts WHERE status = ? AND email= ?";
    $this->db->query($sql, array('active', 'info@primebank.com.bd '));
?>


The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.
in Query Binding Method, you don’t have to escape the values manually as it will automatically do that for you.


Removing SQL injection in Codeigniter using Active Record Class

Using Active Records, query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

Example:
<?
 $this->db->get_where('accounts',array('status' => 'active','email' => 'info@primebank.com.bd'));
?>

No comments:

Post a Comment