Search code examples
phpsqlcodeignitersql-injection

how does codeigniter sanitize inputs?


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?


Solution

  • Exactly like this (for the MySQL driver):

    • Tries mysql_real_escape_string() (this will be the case 99% of the time)
    • Falls back to mysql_escape_string()
    • Falls back to addslashes()
    • Manually escapes % 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.