Welcome Guest, Not a member yet? Register   Sign In
Why my session is not working with error message-Cannot modify header information
#1

[eluser]manojchakri[/eluser]
Hi all.
Now I wrote a login validation form with database checking.Now after successfully logging in for the user I want to create session variable and get the user data from the session information. But When I am creating session it is giving error like "Cannot modify Header Information".My code is like this.
Controller:
Code:
class Form extends Controller
{
    function Form()
    {
        parent::Controller();
            $this->load->library('session');
    }
   function index()
    {
        //$this->load->view('header');
        
        echo $this->session->userdata('user_name');

        $this->load->view('simple');
        $this->load->view('signup');
    }
   function post_form()
    {
        $username = $this->input->post('username');
        echo $username;
        $pwd=$this->input->post('pwd');
        $this->load->model('simpl');
        if($this->simpl->test1($username,$pwd)===TRUE)
        {
            $user=array('user_name'=>$username,'logged_in'=>TRUE);
                        $this->session->set_userdata($user);

                    echo $this->session->userdata('user_name');
            echo '<BR>successfully logged in<a >Back to Home Page</a>';
        }
    }
Here my model test1 function is validating for user data from database and returning true.
But when session is setting user data then the error like this is coming

Quote:A PHP Error was encountered
Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\CodeIgniter_1.7.1\system\application\controllers\form.php:72)

Filename: libraries/Session.php

Line Number: 662
What should I do? I need to display the logged in user name like "welcome <user>" on every page and a logout link which should close the session and display "welcome guest" on every page and login link.Please help me with some sample code..Thanks in advance.
#2

[eluser]Dam1an[/eluser]
This comes up all the time (search anyone?)
It's cause because you prematurely sent some output to the screen, this can be anything, from a string, to a whitespace (eg if you have a newline before the opening PHP tags or after the closing tag)
#3

[eluser]manojchakri[/eluser]
Ok I got it.Thank you.But How do you know some session data is already set in Codeigniter.Is there any thing like isset() here??
#4

[eluser]Dam1an[/eluser]
If you use CI sessions, it will return false if you try to get something which hasn't been set, so you can do something like
Code:
if($this->session->userdata('logged_in')) {
  echo 'Welcome ', $this->session->userdata('user_name');
} else {
  echo 'Welcome guest';
}

(You could also rewrite this using a ternary operator if you prefer)




Theme © iAndrew 2016 - Forum software by © MyBB