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.
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?session_start()outputs to the browser by default, so AFAIK I need theob_start()to make sure theheader()call gets executed. Other than the session this script at the very start. Explanation of Session Output and Redirectssession_startis sending the headers.