INTRO: FIRST: I Know about How to fix "Headers already sent" error in PHP
My question isn't about why it doesn't work. I know why it doesn't work, there is output before header();. My question is why it works for a guy in a YT video, that I am learning from, when he has the same output before header();
POST: I am a super noob PHP programmer, self-learning for just a few weeks. I am trying to do a login system with PHP, learning from a youtube video. I got an error
Cannot modify header information - headers already sent by (output started at Sites/Login/inc/header.php:5...
and I think I know why I got the error.
My code:
index.php
<?php
require_once("inc/header.php");
?>
<?php
if (func::checkLoginState($conn))
{
echo "Welcome" . $_SESSION["username"] . "!";
} else
{
header("location:login.php");
}
?>
<?php
require_once("inc/footer.php");
?>
functions.php (Short version, so it returns false)
<?php
class func {
public static function checkLoginState ($conn)
{
return false;
}
}
?>
header.php
<?php
include_once("config/config.php");
include_once("functions.php");
?>
<html>
<head>
<title>Login project</title>
</head>
<body>
config.php
contains just PDO database connection setup
footer.php
closing HTML tags
Now, if I delete HTML tags from header.php
, the header();
function works. What I can't for the life of me figure out is, why it works for the guy, who I am learning from in the youtube video (he HAS the html tags in header.php).
at 4:30 you can see his header.php
at 6:58 you can see his index.php
(He actually has html code in this file before header(); and at 7:15 it just works..)
at 7:15 you can see index.php
in the browser, it doesn't throw an error and redirects him to login.php
https://youtu.be/3xdxhfNg3Xg?t=4m30s
He HTML tags in the header.php as well and he includes it before the if the function in index.php
. I have exactly the same code basically. Just to shorten it, I returned false in my checkLoginState function, so it does the else part in the function in index.php
. He doesn't use ob_start();
anywhere (which is supposed to solve this somehow).
It's probably some basic thing that I missed but it bugs me so much. Thank you for clarifying this. Also, how am I supposed to redirect to login.php
, since header();
seems kinda useless?
Thank you and have a great day!