0

On each page in an application I have a check to see whether a user is logged in. I recently realized my script was not structured well and made some changes. I am wondering if this new method implements the correct order of operations for a user that is not logged in.

<?php
ob_start();
session_start();

if ($_SESSION['loggedin'] !== true) {
    $_SESSION['messages'][] = '<li>User Not Logged In</li>';
    session_write_close();
    ob_end_clean();
    header('Location: login.php');
    exit;
}
else {
    // execute page
}
?>

Prior to this script, the ob_start() call was below the login check section and therefore was causing redirect issues given that session_start() produces its own headers.

I am also interested in knowing whether the script provides adequate security for a login check.

3
  • 1
    You should not need ob_start(); at the top unless the script is outputting something to the browser before the redirect. Are you including this script in your pages and does the including script send output to the browser before this script is called? Commented Jun 29, 2013 at 20:21
  • @jeroen session_start() outputs to the browser by default, so AFAIK I need the ob_start() to make sure the header() call gets executed. Other than the session this script at the very start. Explanation of Session Output and Redirects Commented Jun 29, 2013 at 20:47
  • No, you cannot start the session if the headers already have been sent. That does not mean that session_start is sending the headers. Commented Jun 30, 2013 at 1:24

1 Answer 1

1

This part of code is complete and secure but you have to mention few things for more security you need to regenerate the session ID with session_regenerate_id after putting valuable data like in 'loggedin' on session.

And I think it is better to put the IF part on a function and omit the else it helps your code be simpler. and Also you can remove the following lines:

session_write_close();
ob_end_clean();
Sign up to request clarification or add additional context in comments.

2 Comments

function makes sense. session_regenerate_id is included in the login script. The ob_end_clean() was added to prevent output of any data to unauthorized users. Why would I remove the other?
You have to check for authenticate before doing anything. If check first you don't have any thing to hide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.