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 Record automatically sanitizes the input, but I'm wondering exactly to what extent? Does it simply escape all the quotes, or does it do more? What about preventing obfuscated SQL injections, or other more advanced kinds?
Basically, I'm looking for an in-depth explanation of how CI sanitizes data. Anyone know?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With