Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Last active September 30, 2015 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/f7b218f8f55e75a3fbab to your computer and use it in GitHub Desktop.
Save kurozumi/f7b218f8f55e75a3fbab to your computer and use it in GitHub Desktop.
【CodeIgniter】Basic認証ライブラリ
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Basic_auth
{
private $username = "username";
private $password = "password";
private $logged_in_key = 'logged_in';
public function __construct(array $config = array())
{
$this->CI = & get_instance();
$this->CI->load->library('session');
if(count($config))
{
$this->initialize($config);
}
}
public function initialize($config = array())
{
foreach ($config as $key => $val)
{
if (isset($this->$key))
{
$method = 'set_'.$key;
if (method_exists($this, $method))
{
$this->$method($val);
}
else
{
$this->$key = $val;
}
}
}
return $this;
}
private function set_username($username)
{
$this->username = $username;
}
private function set_password($password)
{
$this->password = $password;
}
private function get_username()
{
return $this->username;
}
private function get_password()
{
return $this->password;
}
public function login()
{
$logged_in = $this->CI->session->userdata($this->logged_in_key);
if ($logged_in !== true)
{
if ($this->auth())
{
$this->CI->session->set_userdata($this->logged_in_key, true);
} else
{
header('WWW-Authenticate: Basic realm="Private Page"');
set_status_header("401");
die("Please enter a valid username and password");
}
}
}
private function auth()
{
if (!$this->CI->input->server('PHP_AUTH_USER'))
{
return false;
} else
{
if (($this->CI->input->server('PHP_AUTH_USER') == $this->get_username())
&& ($this->CI->input->server('PHP_AUTH_PW') == $this->get_password()))
{
return true;
} else
{
return false;
}
}
}
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
public function basic_auth()
{
$this->load->library('Basic_auth', array(
'username' => 'username',
'password' => 'password'
));
$this->basic_auth->login();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment