Title: PHP Header Isn't working - Page is displayed as usual
Tags: php
Question: I'm trying to prevent direct access to a the following file (and only allow access to those who submitted a form), but when I go right to this file, Instead of 404 I'm seeing the file correctly. Can someone tell what is wrong with this code?
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("HTTP/1.0 404 Not Found");
} else {
if(isset($_POST['a'])){
switch ($_POST['a']){
case "1":
$var = "hey";
break;
case "2":
$var = "now";
break;
default:
$var = "other";
}
?&gt;
<!doctype html&gt;
<html&gt;
<head&gt;
<title&gt;test</title&gt;
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
</head&gt;
<body&gt;
something
</body&gt;
</html&gt;
Comment: You send the HTML anyway.

Comment: Should I also add `ob_end_clean();` like in that thread?

Comment: `exit` after setting the header

Here is the accepted answer: You need to remember to stop executing after you've called 404:
header("HTTP/1.0 404 Not Found");
exit(); // Stop Executing
If you don't, you'll be sending the 404 status code and the HTML, and most browsers would still display the HTML in that case. x
To display an error page
Make an error screen and put it in a file named something like, 404.php, then update the code to:
header("HTTP/1.0 404 Not Found");
include '404.php'; // Display the Not Found error
exit();            // Stop Executing
Comment for this answer: I've added it and now I get a blank page, why am I not getting the error page?
Comment for this answer: Internet Explorer displays a custom error page for 404's without content (known as a "friendly error message") but most other browsers will display what they want, ie a blank screen. If you want to make your own error page, I'd suggest creating one, putting it in a file named 404.php, then adding `include '404.php';`. I'll edit my answer to reflect this :) x

Here is another answer: Add exit; after the 404 header.
Really make sure there is nothing in front of the opening php tag <?php

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:04/02/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<php>', 'Title': "PHP Header Isn't working - Page is displayed as usual", 'ViewCount': 92, 'id': 22809362, 'user_AboutMe': '', 'user_AccountId': 4050129.0, 'user_DisplayName': 'rockyraw', 'user_Reputation': 1125.0, 'user_Views': 200.0, 'user_id': 3330034.0}}