Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 873
John Avatar asked Oct 23 '09 20:10

John


People also ask

Which will 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.

Does Mysqli prevent SQL injection?

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.

Does ORM prevent SQL injection?

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.

Do stored procedures prevent SQL injection?

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.


2 Answers

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.

like image 113
MarioRicalde Avatar answered Sep 20 '22 17:09

MarioRicalde


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:

  1. $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.

like image 40
John Himmelman Avatar answered Sep 20 '22 17:09

John Himmelman