I\'m building a Codeigniter application and I\'m trying my hardest to prevent SQL injections. I\'m using the Active Record method to construct all my queries. I know Active Rec
Exactly like this (for the MySQL driver):
mysql_real_escape_string()
(this will be the case 99% of the time)mysql_escape_string()
addslashes()
%
and _
in LIKE
conditions via str_replace()
https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/drivers/mysql/mysql_driver.php#L294
/**
* Escape String
*
* @access public
* @param string
* @param bool whether or not the string will be used in a LIKE condition
* @return string
*/
function escape_str($str, $like = FALSE)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = $this->escape_str($val, $like);
}
return $str;
}
if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id))
{
$str = mysql_real_escape_string($str, $this->conn_id);
}
elseif (function_exists('mysql_escape_string'))
{
$str = mysql_escape_string($str);
}
else
{
$str = addslashes($str);
}
// escape LIKE condition wildcards
if ($like === TRUE)
{
$str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
}
return $str;
}
Note that this is merely escaping characters so MySQL queries will not break or do something unexpected, and is used only in the context of a database query to ensure correct syntax based on what you pass to it.
There is no magic that makes all data safe for any context (like HTML, CSV, or XML output), and just in case you were thinking about it: xss_clean()
is not a one-size-fits-all solution nor is it 100% bulletproof, sometimes it's actually quite inappropriate. The Active Record class does the query escaping automatically, but for everything else you should be escaping/sanitizing data manually in the correct way for the given context, with your output, not your input.
You can always see the latest query made by using the last_query()
method.
$this->db->last_query()
You will see exactly how the query looked, so you can verify if sanitized properly.
Active Record only escapes the data, nothing else. SQL injection is prevented by escaping. Then use validation on the forms with their validation class. Should take care of your issues. Here's the link for the other CodeIgniter security items:
CodeIgniter UserGuide Security