[eluser]Unknown[/eluser]
I just finished up a portfolio site for a friend, and could not find an uber simple codeigniter library or helper that just leveraged basic authentication. I didn't want to manage users, registrations, and so forth when all we needed was to make sure only he and I could access the control panel.
Here's the code. Suggestions are welcome, this site is my first CI project and one of my first PHP projects.
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
//
// Basic401Auth
// Version 0.1
// Coded by Nathan Koch on 12-23-2008
// Just add
//
// $this->load->library('basic401auth');
// $this->Basic401Auth->require_login()
//
// anywhere you need basic authentication
class Basic401Auth
{
function __construct()
{
$this->ci =& get_instance();
}
function headers_401()
{
$user = $this->ci->config->item('admin_user');
$password = $this->ci->config->item('admin_pw');
if ( !isset($_SERVER['PHP_AUTH_USER']) )
{
header('WWW-Authenticate: Basic realm="SMF Studios"');
header('HTTP/1.0 401 Unauthorized');
echo("Please enter a valid username and password");
exit();
}
else if ( ($_SERVER['PHP_AUTH_USER'] == $user) && ($_SERVER['PHP_AUTH_PW'] == $password) )
{
return true;
}
else
{
echo("Please enter a valid username and password");
exit();
}
}
function require_login()
{
$logged_in = $this->ci->session->userdata('logged_in');
if ( $logged_in != TRUE)
{
$this->headers_401();
$this->ci->session->set_userdata( array('logged_in' => TRUE) );
}
}
}
?>