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?
How to Prevent an SQL Injection. The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly.
Another way you can protect your code against SQL injections is by using prepared statements. Prepared statements are precompiled SQL commands. They can be used with a specific database access library (such as mysqli) or with the more generic library PDO.
The benefits of using an ORM tool include quick generation of an object layer to communicate to a relational database, standardize code templates for these objects, and that they usually provide a set of safe functions to protect against SQL Injection attacks.
All the input values should be validated before putting them under code to perform database transactions. Use of Stored Procedures (in right way) reduces risk of SQL Injection Attack.
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.
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.
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