Does CodeIgniter automatically prevent SQL injection?
I just inherited a project because the last developer left. The project is built off of Code Igniter. I've never worked with Code Igniter before.
I took a quick look at the code and I see database calls in the controller like this:
$dbResult = $this->db->query("SELECT * FROM users WHERE username = '".$_POST['user_name']."'");
or calls like this:
$dbResult = $this->db->query("SELECT * FROM users WHERE username = '".$this->input->post('username')."'");
Does code igniter automatically sanitize these queries to prevent sql injection?
Solution 1:
CodeIgniter DOES ESCAPE the variables you pass by when using the $this->db->query
method. But ONLY when you pass the variables as binds, here's an example:
$dbResult = $this->db->query("SELECT * FROM users WHERE username = ?", array($this->input->post('username')));
Also remember that $_POST
shouldn't be preferred over $this->input->post
since what it does is check if the variables exists to prevent errors.
Solution 2:
CodeIgniter provides a few string escaping functions in its database layer.
Excerpt from CI Manual:
It's a very good security practice to escape your data before submitting it into your database. CodeIgniter has three methods that help you do this:
$this->db->escape() This function 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:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
I'd post the other two examples, but I wouldn't want to take all the fun out of reading the manual.
Solution 3:
No, the code you posted is susceptible to SQL injection. You need to use query binding to construct your SQL queries. If you're using the CI DB library, you would code it something like this (example from the user guide):
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
Solution 4:
No, CodeIgniter will not magically sanitize queries which have been built like this.