1

Hello I want to know why this kind of example question never been asked before. I got this code from my college that they say this kind of code is able to prevent SQL injection.
We use CodeIgniter to build a website and here is the code to prevent SQL injection.

Controller:

$usr = $this->input->post('userid');
$pwd = $this->input->post('passwd');

if($usr && $pwd) {
                $ack = $this->mAuth->get_user($usr);
$pwx = $ack['passwd'];
                    if($ack && $pwd == $pwx) {
                        //redirect code
}

Model:

public function get_user($user_id='', $status=1) {
        $user_id = $this->db->escape(trim($user_id));
        $status  = $status ? 'and user_status_uid = 1' : '';

        $sql = "select * from users where user_id = lower($user_id)"

        return rst2Array($sql, 'row');
    }

I tried to login with 1' or 1 = 1 and etc, I found and it did prevent SQL injection even though it's only a plain text and password.

Is there any vulnerability to this code? thanks

  • I am not familiar with Codeigniter nor it's functions and syntax so I cannot comment on if "$this->db->escape(trim($user_id));" escapes and sanitzes the input properly. Also please note that SQL injection is not limited to "1' or 1 = 1". If you can explain what that function does sanitation entails it would be easier to answer the question of if there are potential vulnerabilities. – ilikebeets Aug 15 '14 at 3:52
3

This sort of question has likely never been asked here before because it is more suitable for StackOverflow.

There are easier and better ways to protect against SQL injection in Codeigniter - I strongly suggest you look at Query Binding (at the bottom of the linked page) or Active Records. Both of these will escape queries for you in a way that is much easier to do and harder to accidentally forget. I have developed and mantained several Codeigniter websites, and Query Binding & Active Record are much better ways to protect your database, as you're less likely to miss escaping a parameter.

What you have is safe from SQL injection (provided Codeigniter's db->escape function works properly, which to the best of my knowledge it does), but if at any point you forget to escape even one thing that goes into your query, then you'll be vulnerable to SQL injection.

If this is for a college assignment then this remark isn't terribly applicable, but outside of academia, storing passwords in plain text is considered terrible security practice. It is much better to use crypt with a per user salt, or password_hash if your PHP installation is recent enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.