Im getting following error in live server, when user login, is sent to dashboard.
warning:session_start():cannot start session when headers already sent in … on line 3
warning:cannot modify header information-header already sent by(output started at…)in…on line 5
login.php code
<?php
ob_start();
session_start();
?>
<?php
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
try {
$data = $conn->prepare("SELECT * FROM users WHERE username = :username");
$data->bindParam(':username', $username, PDO::PARAM_STR);
$data->execute();
} catch (PDOException $e) {
$e->getMessage();
die("Something went wrong please contact your adminstrator");
}
while($rows = $data->fetch(PDO::FETCH_OBJ) ){
$user_id = $rows->user_id;
$db_username = $rows->username;
$db_password = $rows->password;
$db_user_role = $rows->user_role;
$db_user_image = $rows->user_image;
}
$verifyPassword = password_verify($password, $db_password );
if($username === $db_username && $verifyPassword){
$_SESSION['username'] = $db_username;
$_SESSION['user_role'] = $db_user_role;
$_SESSION['user_image'] = $db_user_image;
$_SESSION['message'] = '';
$_SESSION['IS_LOGIN']='yes';
header('Location:admin');
}else{
//header('Location:index.php');
echo "<script>alert('Invalid Paswword')</script>";
}
}
?>
After successful login its redirect to dashboard im getting error in this page.
warning:session_start():cannot start session when headers already sent in … on line 3
warning:cannot modify header information-header already sent by(output started at…)in…on line 5
<?php
ob_start();
session_start();//line 3
if(!isset($_SESSION['user_role'])){
header('Location:../index.php');//line 5
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
CodePudding user response:
header() always has to be the first thing on your page:
<html></html>
<?php header('location: xy'); ?>
Output:
Warning: Cannot modify header information - headers already sent by (output started at /home/user/scripts/code.php:1) in /home/user/scripts/code.php on line 2
Instead:
<?php header('location: xy'); ?>
<html></html>
Throws no error
So either you have to use header() at the top or you have to use pure html for the redirect:
<meta http-equiv="refresh" content="0; url=http://example.com/" />
CodePudding user response:
If your php version PHP >= 5.4.0 , PHP 7, PHP 8
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
else PHP < 5.4.0
if(session_id() == '') {
session_start();
}
If it is work/does not work give me feedback so I will try another way.