0

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";
      }
    }
  }
?>  
<!doctype html>
<html>
  <head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>
    something
  </body>
</html>
Albzi
  • 15,431
  • 6
  • 46
  • 63
rockyraw
  • 1,125
  • 2
  • 15
  • 36

2 Answers2

1

Add exit; after the 404 header.

Really make sure there is nothing in front of the opening php tag <?php

blue
  • 1,939
  • 1
  • 11
  • 8
1

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
Emily Shepherd
  • 1,369
  • 9
  • 20
  • I've added it and now I get a blank page, why am I not getting the error page? – rockyraw Apr 02 '14 at 11:08
  • 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 – Emily Shepherd Apr 02 '14 at 11:10