0

I am trying redirect user when login successfully but I am getting error on entering wrong username and password and also redirection not working. If I insert valid username and password works great.

Error:

Notice: Undefined offset: 0 in /var/sites/l/example.com/public_html/demo/sitename/application/models/loginmodel.php on line 70

Notice: Trying to get property of non-object in /var/sites/l/example.com/public_html/demo/sitename/application/models/loginmodel.php on line 70

Warning: Cannot modify header information - headers already sent by (output started at /var/sites/l/example.com/public_html/demo/sitename/application/models/loginmodel.php:70) in /var/sites/l/example.com/public_html/demo/sitename/application/models/loginmodel.php on line 82

My Code:

session_start();

        $username = strip_tags($username);
        $password = strip_tags($password);

        $sql = "SELECT id FROM users WHERE name='$username' and password='$password'";
        $query = $this->db->prepare($sql);
        $query->execute();
        $records = $query->fetchAll();
        $ck_userID = $records[0]->id;
        //$active=$row['active'];
        // echo "<pre>";
            // print_r($ck_userID);
        // echo "</pre>";
        // die;

        if ( count($ck_userID) > 0 ){ 
            $_SESSION['login_user']=$username;
            header('location: ' . URL . 'admin');
        }else{
            header('location: ' . URL . 'login?invalid');
        }
Anand Solanki
  • 3,419
  • 4
  • 16
  • 27
Mr.Happy
  • 2,639
  • 9
  • 40
  • 73

2 Answers2

0

change

   $records = $query->fetchAll();
   $ck_userID = $records[0]->id;
   if ( count($ck_userID) > 0 ){ 

to

   $records = $query->fetchAll();
   if ( count($records) > 0 ){ 

NOTE: your code is vulnerable to sql injections

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
0

Change

$ck_userID = $records[0]->id;

to

$ck_userID = isset($records[0]) && is_object($records[0]) ? $records[0]->id : null;

Explanation:

You have to check whethe $records[0] does exist and you should check whether it's an object (so it's not false or null).

Also care for SQL injection. You are using some kind of prepare method, but you don't prepare anything.

Another bad practice is header sending location change but no exit following. Header start with a capital letter, location: -> Location:.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151