Send 404 header via PHP after .htaccess redirect

wheeey-

I want to create a custom 404 page but it won't send the 404 Header, it still send's 200 OK.

.htaccess

My .htaccess redirects every request to index.php.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.php [NC,L]

index.php

The index.php handles the url with included .php files. Actually controller.php parses the URL and finally pasteContent.php includes the requested .php content-file.

//Handle URL
  require 'inc/controller.php';

//Paste <head>
  require 'inc/site_header.php';

//Paste <body>
  require 'inc/pasteContent.php';

//Paste footer
  require 'inc/site_footer.php';

A closer look to controller.php:

As you can see I already tried to send 404-Header, before there is any output.

//Parse the URL
function parse_path() {
    [...]
    return $path;
}

$path_info = parse_path();
$controller = $path_info['call_parts'][0];

//Does this page exist?
function contentFound($c){
    $found = true;
    switch ($c) {
      [...]
        default:
            $found = false;
    } return $found;
}

//If content does not exist -> 404
if(!contentFound($controller)) {
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
    require 'inc/site_header.php';
    require 'inc/pasteContent.php';
    require 'inc/site_footer.php';
    die();
}

Actually I also tried to put header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");? on top of my index.php, where we get redirected to but it still sends 200 OK. What am I doing wrong?

Jan Papenbrock

As KIMB-technologies pointed out in his previous answer to this question, whitespace causes this problem. If you cannot find any visible whitespace at the beginning of any of your PHP files, there might be an invisible whitespace on them, though.

Sometimes the UTF-8 BOM (Byte Order Mark) is present on some files. It is invisible to text editors, but messes up PHP headers.

Google for ways to remove it appropriate for your OS, using Bash, Powershell or something. Some IDE, such as PhpStorm, offer the removal directly.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related