Hi there! Welcome to our blog. Don't forget to sign up for our free RSS feed. We Triple Dog Dare Ya! And thanks for visiting!
Recently, I was working on a CodeIgniter site for a customer. They wanted to go live with the site’s domain, but they wanted to hide everything on the site behind a very simple password that only the site owners would know. That way only the development team and a few internal stakeholders would have access.
Adding this kind of password protection is pretty easy in CodeIgniter. All you have to do is add a quick check in your main controller’s constructor to see if a session variable has been set. For example:
class Welcome extends Controller {
function __construct(){
parent::Controller();
session_start();
if ($_SESSION['loggedin'] != true){
redirect('protect/preview','refresh');
}
}//end controller init
//rest of controller excised
}
Create a second controller called protect.php and set up a preview() function inside of it. The preview() function checks to see if a POST has been passed to it. If it has, simply check to see if the string from the password field matches the secret password. In this case, we are hard-coding the password right in the controller, but you could just as easily grab it from an XML file or database table.
If the password matches, set the session value for loggedin to true, then send them back to the original welcome controller. Otherwise, show the view.
Here’s the protect controller:
class Protect extends Controller {
function __construct(){
parent::Controller();
session_start();
}//end controller init
function preview(){
if ($_POST){
if (strtolower($this->input->post('pw')) == "mypassword"){
$_SESSION['loggedin'] = true;
redirect('welcome/index','refresh');
}else{
$this->session->set_flashdata('warning',"Wrong Password!");
redirect('protect/preview','refresh');
}
}else{
$data['title'] = "No sneak peeks allowed!";
$this->load->vars($data);
$this->load->view('preview_template');
}
}
}//end class
Finally, create a very simple preview_template view to hold the form and display any warning messages that are stored in CodeIgniter 1.6’s new flashdata component:
<h1><?php echo $title;?></h1>
<p>You have to login to see the site! Sorry about that.
<b style='color:red'>
<?php echo $this->session->flashdata('warning');?>
</b></p>
<?php
echo form_open('protect/preview');
echo form_password('pw');
echo form_submit('submit','get sneak peek');
?>
Tags: 1 Comment



1 response so far ↓
man hear it.. IN GREAT CAPITAL LETTERS
THANKS!!
I was reading a F… book about Codeigniter and the author is so proud of himself that maybe he could’nt get time to explaing the more simple things like this.
You were my savior today THK AGAIN!!!!!!!!
(SORRY FOR THE POOR ENGLISH I’M STILL LEARNING)