HTML code:
login.php :
<body><div class="container-fluid" style="margin-top: 170px; margin-bottom: 150px"><header><?php require('header.php'); ?></header><?php require('navbar-login.php'); ?><?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { require('process-login.php'); } ?>...
PHP code:
navbar-login.php :
<div class="row fixed-top py-2" style="margin-top: 86px; background-color: #c0c0c0"><div class="col-xl-8 col-lg-8 col-md-8 col-sm-9 col-8"></div><div class="col-xl-4 col-lg-4 col-md-4 col-sm-3 col-4"><nav><div class="btn-group" role="group"><button type="button" class="btn btn-outline-secondary" onclick="location.href = 'index.php'"><i class="fa-solid fa-house"></i></button><button type="button" class="btn btn-outline-secondary" onclick="location.href = 'form-register.php'"><i class="fa-solid fa-address-card"></i></button></div></nav></div></div>
process-login.php :
<?phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { try { $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); if ((empty($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) { $errors[] = '<strong>No email</strong>: check.'; } $password = filter_var( $_POST['password'], FILTER_SANITIZE_STRING); if (empty($password)) { $errors[] = '<strong>No password</strong>: check.'; } if (empty($errors)) { require ('mysqli_connect.php'); $query = "SELECT user_id, name, surname, password FROM table WHERE email=?"; $q = mysqli_stmt_init($dbcon); mysqli_stmt_prepare($q, $query); mysqli_stmt_bind_param($q, "s", $email); mysqli_stmt_execute($q); $result = mysqli_stmt_get_result($q); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); if (mysqli_num_rows($result) == 1) { if (password_verify($password, $row['password'])) { session_start(); $_SESSION['user_id'] = (int) $row['user_id']; $_SESSION['name'] = (string) $row['name']; $_SESSION['surname'] = (string) $row['surname']; mysqli_stmt_free_result($q); $dbcon->close(); header('Location: dashboard.php'); exit(); } else {......
If I comment the line <?php require('navbar-login.php'); ?>
in the HTML login.php file, it's ok. Else I get the warning: PHP Warning: session_start(): Cannot start session when headers already sent
.I know that no code can be before session_start()
and that the problem is the navbar, but I need the navbar to navigate!I used the same code explained in "Practical PHP 7, MySQL 8, and MariaDB Website Databases" by Adrian W. West & Steve Prettyman.Where did I go wrong?