0

When I try to logout of the session I created I keep getting modify header errors.. Here is my code

   function logout()
 {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('home', 'refresh');
 }

Here are the errors:

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Users/Rob/stage/dashboard.php:36)

Filename: libraries/Session.php

Line Number: 688

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Users/Rob/stage/dashboard.php:36)

Filename: helpers/url_helper.php

Line Number: 540

Any ideas what would cause this?

This is my entire controller for the the code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class dashboard extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('dashboard', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('home', 'refresh');
 }

}

?>

I basically just log the user into a view and then there is a logout link on that page which when they click it they then get logged out of the session which then runs the logout function. Any ideas?

Robert
  • 343
  • 6
  • 16
  • You did print something out before sending the header (calling logout function). Ensure, that `logout()` is called before any `echo` statement. – ConcurrentHashMap Aug 25 '14 at 20:12
  • 1
    possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – M Khalid Junaid Aug 25 '14 at 20:26

2 Answers2

1

This answer will most likely resolve your issue.

However, as I cannot comment, I'd like to point out that if you are going to destroy the session you don't need to unset any part of it first. Therefore can change the following

 $this->session->unset_userdata('logged_in');
 session_destroy();

to this:

 $this->session->sess_destroy();
Community
  • 1
  • 1
JonathanBristow
  • 1,066
  • 2
  • 13
  • 36
1

Also to add, use

$this->session->sess_destroy();

instead of session_destroy().

ChrisG
  • 675
  • 6
  • 13