• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

[Solved] HTTP Authentication Basic Using Codeigniter And MySql

Web & Mobile Developer
Staff member
Here is what i done when need http authentication basic on Codeigniter using MySql as database.
PHP:
 function auth() {
  $authorized = false;
  $username = isset($_SERVER['PHP_AUTH_USER'])?$_SERVER['PHP_AUTH_USER']:'';
  $password = isset($_SERVER['PHP_AUTH_PW'])?$_SERVER['PHP_AUTH_PW']:'';
  header('Cache-Control: no-cache, must-revalidate, max-age=0');
  $query = $this->db->select("Sopir, password")
          ->from("sopir")
          ->limit(1)
          ->where("Sopir", $username);
  $result = $query->get();
 
  if ($result->num_rows() > 0) {
   $sopir = $result->result();
    if (password_verify($password, $sopir[0]->password)) {
     $authorized = true;
    }else{
     $authorized = false;
    }
  }

  if ($authorized === false) {
   header('HTTP/1.1 401 Authorization Required');
   header('WWW-Authenticate: Basic realm="What do you need from this site?"');
   echo "You must enter a valid login ID and password to access this resource\n";
   exit;
  }
 }
We just only need change the query above as we want. We can get username entered by user using this $_SERVER['PHP_AUTH_USER'] and take password entered using $_SERVER['PHP_AUTH_PW'] then we compare those data with data suplied from MySQL.

I am used password_verify() to verify user password. And stored user password using password_hash() function.