I am testing my login on a new demo website I am doing. I can actually login, and I get my username returned from the database, but I get the following error in the top:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/MAMP/htdocs/websiteNew/testlogin.php:1) in /Applications/MAMP/htdocs/websiteNew/resources/auth/session.php on line 3
Why do I get that error? I understand that the error can be caused, if I call include files before I call the session. But I cannot see I am doing that here?
NOTE: Updated code:
header.html
<?php
$error='';
if( !isset( $_SESSION ) ) session_start();
if( !isset( $_SESSION['username'])) include('resources/auth/login.php');
else exit( header('Location: testlogin.php') );
?>
<html>
<body>
<!-- Navigation code -->
index.php
<?php include 'resources/includes/header.html' ?>
// Content Code
</body>
</html>
login.php
<?php
/* login.php */
if( !isset( $_SESSION ) ) session_start();
include 'resources/dbconnect/dbconfig.inc.php';
$error = '';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'] ) ) {
if( empty( $_POST['username'] ) || empty( $_POST['password'] ) ){
$error = 'Both fields are required.';
} else {
$sql='SELECT `u_id`, `username` FROM `login` WHERE `username`=? AND md5(`password` )=? limit 1 ';
$stmt=$mysqli->prepare( $sql );
if( !$stmt ) exit('Failed to prepare sql statement');
$username=$_POST['username'];
$password=md5( $_POST['password'] );
$stmt->bind_param('ss', $username, $password );
$res=$stmt->execute();
$login_user = null;
$user_name = null;
/* bind result to variable */
$stmt->bind_result( $login_user, $user_name );
while( $stmt->fetch() ){
$_SESSION['u_id'] = $login_user;
$_SESSION['username'] = $user_name;
}
$stmt->close();
$mysqli->close();
if( isset( $_SESSION['username'] ) ) exit( header( 'location: index.php' ) );
else $error='Incorrect username or password.';
}
}
?>
session.php
<?php
if( !isset( $_SESSION ) ) session_start();
if( !isset( $_SESSION['username'] ) ) exit( header('Location: index.php')
// Above is line 3
);
?>
testlogin.php
<?php
include 'resources/auth/session.php'; // If I only add this line I do not get any error
include 'resources/includes/header.html'; // If I add the line I get the error in my question. But I need to include my header
?>
<!-- *** USER LOGGED IN ***-->
<?php
if ( isset( $_SESSION['username'] ) )
{
?>
<en><?php echo $_SESSION['username'];?></en><span class="caret"></span>
<a href="index.php">Log Out</a>
<!-- *** USER NOT LOGGED IN ***-->
<?php
}
?>