0

Below is the code I use in my Codeigniter project for logging in an admin user

public function login()
{
    $usename = $this->input->post('username');
    $password = $this->input->post('password');

    $this->db->where('username', $username);
    $this->db->where('password', MD5($password));
    $this->db->limit(1);
    $query = $this->db->get('user');

    if($query->num_rows() == 1)
        return true; // login the user
    else
        return false; // user not found
}

When the query is echoed

echo $this->db->last_query();

it outputs something like this:

SELECT * FROM (`user`) WHERE `username` = 'admin' 
    AND `password` = '5f4dcc3b5aa765d61d8327deb882cf99' LIMIT 1

Now when I input the password as value)'; DROP TABLE user;--, the query produced is :-

SELECT * FROM (`user`) WHERE `username` = 'admin' 
    AND `password` = 'c0b24ab68e0f79e23ebec36e36a5309f' LIMIT 1

So I guess it is pretty much safe from sql injection because codeigniter active record is automatically escaping the input data.

Edit based on comment

Now username is input with something like this username'; DROP TABLE user;-- then, the query produced is

SELECT * FROM (`user`) WHERE `username` = 'username\'; DROP TABLE user;--' 
    AND `password` = '5f4dcc3b5aa765d61d8327deb882cf99' LIMIT 1 

So I guess it is escaping in that case also.

But my question is, whether the above code is really sufficient enough to prevent all the possible sql injection attacks?

Adersh
  • 598
  • 1
  • 9
  • 22
  • 2
    In this case it's safe because you ***hash*** the input. CI may or may not be correctly escaping values in addition, but that's not the primary reason it's safe in this case. – deceze Apr 11 '16 at 16:00
  • 4
    Have you tried adding the drop table magic into the username field? What happens to that query? – WillardSolutions Apr 11 '16 at 16:02
  • 1
    @EatPeanutButter It really messes up the query. I didn't check that. :) – Adersh Apr 11 '16 at 16:04
  • 1
    @EatPeanutButter I think it is escaping in that case also. Plz check the edit – Adersh Apr 11 '16 at 16:19
  • 1
    So that gives you more info about how CI is working behind the scenes. You should also read this: http://stackoverflow.com/questions/1615792/does-codeigniter-automatically-prevent-sql-injection – WillardSolutions Apr 11 '16 at 16:22

0 Answers0