CodeIgniter: View doesn't load if I use die() function - php

I have the following code. Checks if the user is logged in or not.
When the variable $is_logged_in is not set or is False, I load a message view.
Unfortunately, at the same time the system loads the restricted content view.
So I used die() function, and now only shows a blank page.
What can I do to only load the message view when the user is not logged in?
Thanks.
if(!isset($is_logged_in) OR $is_logged_in == FALSE)
{
$data['main_content'] = 'not_logged_in';
$data['data'] = '';
$this->load->view('includes/template',$data);
die();
}

Actually, I've found an answer to mantain the URL and not redirect:
$data['main_content'] = 'unauthorized_access';
$this->load->view('includes/template', $data);
// Force the CI engine to render the content generated until now
$this->CI =& get_instance();
$this->CI->output->_display();
die();

Anyway. I used a redirect to the login page, and a flashdata variable
if(!isset($is_logged_in) OR $is_logged_in == FALSE)
{
$this->session->set_flashdata('error_msg','You must be logged in to access restricted area');
redirect('login/');
}
Thanks

I've been messing around with this for a while. If you're using die or exit after trying to load a view, CI shows a blank page.
The solution would be to use return, which stops execution of the current function, and does not execute anything after below that.
A simple example:
public function validate(){
//validation code
if(!$valid){
$this->load->view('error');
return;
}
//This code won't run
}

CI is probably using output buffering (see http://www.php.net/manual/en/ref.outcontrol.php). If you want to load a view and kill the script, you will need to flush the buffer. This would normally be done at the very end of the script, but die()ing stops it from getting there.
if(!isset($is_logged_in) OR $is_logged_in == FALSE)
{
$data['main_content'] = 'not_logged_in';
$data['data'] = '';
$this->load->view('includes/template',$data);
ob_flush();
die();
}

Related

How to redirect back to previous page after login in Code Igniter?

Okay, so this is what I do:
I go to www.mywebsite.com/orders?id=1
It redirects be to login before proceeding.
I log in successfully but it redirects to www.mywebsite.com/orders.
If I am already logged in and go directly using GET method, it works fine. But if I am asked to login, the GET method disappears.
How do I preserve ?id=1?
Before redirecting the user back to the login page store the current page (the requested page) in a session variable. Assuming you have a function called check_login this would more or less look like what you should do:
public function check_login() {
if (!$this->session->has_userdata('logged_in') || $this->session->logged_in !== true) {
if (!empty($_SERVER['QUERY_STRING'])) {
$uri = uri_string() . '?' . $_SERVER['QUERY_STRING'];
} else {
$uri = uri_string();
}
$this->session->set_userdata('redirect', $uri);
redirect('/auth/login');
}
}
Then when the user successfully logs in your login function should somewhere have the following logic:
public function login() {
// form validation
// get post vars
// check username/pwd against db
if ($login) {
if ($this->session->has_userdata('redirect')) {
redirect($this->session->redirect);
} else {
redirect('/dashboard');
}
} else {
// error logging in
}
}
session variable could store the id.While log in using session pass the id value.You can retrive the value anywhere in session.
$this->load->library('session');
$this->session->set_userdata('userId', 'YourId');
where userId would be the name of the session variable, and YourId would be the value.
Simply Use this
redirect($_SERVER['HTTP_REFERER']);

Codeigniter View gives error

I am developing a web application with codeigniter. I have a main screen which loads three views as follows:
1)header 2)main screen 3)footer
the 'main_screen' view loads another view called 'login'
here is the code
<?php
if($logged == null){
$CI = &get_instance();
$CI->load->view('login');
}else{
echo $logged;
$CI = &get_instance();
$CI->load->view('login');
}
?>
the variable $logged is actually a data sent by a controller, when I first time loads the page it gives error 'Undefined, variable', but when i login it doesn't, here is the code.
if($loginSucessfull){
$data['logged'] ='<div class="success">Login Sucessfull</div>';
$this->load->view('header');
//here I am sending data to the 'menu_screen'
$this->load->view('menu_screen',$data);
$this->load->view('footer');
} else {
$data['logged'] = '<div class="alert">Sorry the username or password is incorrect</div>';
$this->load->view('header');
//here again I am sending the data
$this->load->view('menu_screen',$data);
$this->load->view('footer');
}
What I am trying to do is, if the user is sucessfully logged in show the sucessfull message else show the error and the login form as well. please help me how to fix this.
$logged isn't null. You get the error because the variable does not exist.
You have to set $logged to something before the main_screen page loads.
I don't know whether it works or not. Just try:
data = array();
$data['logged'] = 'something that you want to assign';

What causes the session to be recreated or to be gone after a page refresh?

I am using codeigniter on my project, and I have a login module and I authenticate each module. When the session does not exist then redirect to the login page. So, this works but sometimes it may happen when I login and then refresh the page I get redirected to the login page (meaning the session is gone).
Please do not try to tell me to use another library such as php native etc. I just want to know what the problem causing this is.
function _admin_login()
{
$this->form_validation->set_rules($this->login_rules);
$data['title'] = "Login";
$data['form_url'] = $this->uri->uri_string();
$data['login_btn'] = form_submit('login','Sign In','class="btn btn-large btn-block btn-primary"');
if($this->form_validation->run($this) == FALSE){
$data['user'] = form_input('username','','class="input-block-level input-large" placeholder="Username"');
$data['passw'] = form_password('password','','class="input-block-level input-large" placeholder="Password"');
$this->template->set('title','Login');
$this->template->load('template_login','login_view',$data);
}else{
$username = $this->input->post('username',true);
$row = $this->authentication_model->get_user_info($username);
$this->session->set_userdata('user',$row['user_id']);
$this->session->set_userdata('username',$row['username']);
$this->session->set_userdata('login_state',true);
$this->authentication_model->update_last_login();
redirect('product');
}
}
This is my login script, if the validation passes then the session is set... and in every controller I have checked the session script. Example below:
$this->authentication_plugin->check_logged_in();
function check_logged_in()
{
if(logged_in() === FALSE){
set_alert('Login in to view this page!!','error');
set_bookmark('login_url');
redirect("login");
}
}
function logged_in()
{
$CI =& get_instance();
$user = $CI->session->userdata('user');
if(!$CI->load->library('session')){
echo "no session is loaded";
die;
}
if(!empty($user)){
return true;
}else{
return false;
}
}
Any ideas? Thanks!
autoload the session library and remove that from your login script.
In config/autoload.php look for $autoload['libraries']
add 'session'
in config/config.php
scroll down to cookie configs and look for $config['sess_cookie_name']
make sure there is no underscore in the cookie name. you have to change the codeigniter default name to do this.
test by doing session checks in the constructor. its a quick sanity check to see if the sessions are working or not.

Codeigniter session authentification still allows restricted page to load

I am trying to restrict access from a page if the user is not logged in. The weird thing is that the webpage, when tried to be accessed by an unauthorised user, shows the page for the restricted access (with the "unauthorised, please login" message and, on the same page, it loads the members only page).
For the site controller:
class Site extends CI_Controller {
function __construct(){
parent::__construct();
$isLogged=$this->session->userdata('logged');
if($isLogged!='logged' || !isset($isLogged)){
$data['content']='denied';
$this->load->view('include/template', $data);
}
}
function members(){
$data['content']='memberArea';
$this->load->view('include/template', $data);
}
The login form :
class Login extends CI_Controller {
function index () {
$data['content']='loginForm';
$this->load->view('include/template', $data);
}
function validateMember(){
// load the model for the login authentification
$this->load->model('loginModel');
//query should also contain the user details
$query = $this->loginModel->authenticate();
//if it returns something:
if($query){
foreach ($query as $row){
//set user data to be passed
$details=array(
'username'=>$row->user_name,
'id'=>$row->id,
'logged'=>'logged',);
}
//set session
$this->session->set_userdata($details);
redirect('site/members');
}
else{
$this->index();
}
}
The model for the login is:
class LoginModel extends CI_Model {
function authenticate(){
//select active fields
$this->db->select('id, user_name, password');
// query to select from table where conditions
$query = $this->db->get_where('login', array(
'user_name'=>$this->input->post('username'),
'password'=>$this->input->post('password'),),
1);
//if it finds something...must ask if i need to manually close the database with $this->db->close();
if($query->num_rows()==1){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
else {return false;}
}
}
My tests showed that site continues to call the other functions even if the construct function fails. the session does contain the data. If i use die() or exit() the webpages loads blank. many thanks in advance!
PS: the views only have <p> in them, nothing fancy.
I can see two solutions to this problem.
Redirect to another page that doesn't check for authentication. You can use redirect(<url>); from the URL helper.
Use exit() in the __construct() with the buffered output flushed. When you call $this->load->view() the data is sent to a buffer called output in CodeIgniter. You can write that buffer by doing :
if($isLogged!='logged' || !isset($isLogged)){
$data['content']='denied';
$this->load->view('include/template', $data);
// Write the output.
echo $this->output->get_output();
// Stop the execution of the script.
exit();
}
or you can by-pass the output buffer with:
if($isLogged!='logged' || !isset($isLogged)){
$data['content']='denied';
// Writes the content instead of sending it to the buffer.
echo $this->load->view('include/template', $data, true);
// Stop the execution of the script.
exit();
}
Pick which ever you want.
The constructor method does not "fail", the if statement is simply executed (because the condition is true) and there is no reason why this would prevent other methods from being executed.
Inside the constructor method, at the end of the if block, you may insert an exit statement, this way the page would probably behave as you are expecting.
See here http://php.net/manual/en/function.exit.php
You're testing if there is a query, not if the query actually return anything. Check the num rows and make sure they equal 1, doing greater than 0 is bad practice on login checks.
if($query->num_rows==1){
PS. Post your model code as well, it's possible the error is there and it's returning a result even when it shouldn't.

Fatal error: Call to undefined function logged_in()

I made a login script, when I want to check when the user is logged in, I use the function logged_in(), which consists of:
function logged_in()
{
if(isset($_SESSION['id']))
{
return true;
}
else
{
return false;
}
}
the session is set here:
else if ($login === true)
{
echo 'Login success.';
include 'include/aside.php';
include 'include/footer.php';
$userid = id_from_username($username);
$usernameforsession = username_from_id($userid);
$_SESSION['id'] = $userid;
$_SESSION['username'] = $usernameforsession;
header( "refresh:2;url=index.php");
exit();
}
And this is an example of me using it in 'index.php':
if(logged_in() === true)
{
echo 'Site content when user is logged in.';
} else if(logged_in() === false)
{
include 'include/widgets/register.php'; //registration form
}
And yes, the function is included in every page.
I made this function so it should work...
Why isn't it working?
Replace this code:
if(logged_in() === true)
With this code:
if(isset($_SESSION['id']))
That cuts out all the middlemen.
Although you have listed quite a bit of code, are you sure you are including session_start(); at the top of each page? You need to call this before you do anything at all with the session variables.
The second thing is that the error message is showing that the function isn't defined - are you sure you have it either in the source for the page or as an include to the code that defines it on each page?
If you have it in a file called 'functs.php', you need to include() it in every page that will make a call to that function.
If you are absolutely sure that the declaration is being included on every page, then I would suggest that you check to make sure the function is not declared as a method inside an object.

Categories