how does codeigniter sanitize inputs?

杀马特。学长 韩版系。学妹 提交于 2019-12-03 02:40:02

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.

TSquared

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

Bojan Bjelic

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!