Reputation: 83
I want to create a custom 404 page but it won't send the 404 Header, it still send's 200 OK.
My .htaccess redirects every request to index.php.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.php [NC,L]
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';
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?
Upvotes: 2
Views: 493
Reputation: 1037
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.
Upvotes: 1
Reputation: 889
Make sure that the headers and the content (sending starts if whitespace are before <?php
) are not already sent by PHP.
if (headers_sent($filename, $linenum)) {
echo "Headers sent in $filename on line $linenum\n";
exit;
}
Maybe you will see, what's wrong, if you know which file starts the output on which line.
As a workaround you can use output buffering:
Insert at the top of the index.php ob_start();
and PHP will wait until the script is terminated before it sends any content.
You can define the protocol directly like this <?php
header("HTTP/1.0 404 Not Found");
?>
, also you can try to reset the status code by using http_response_code(404);
Upvotes: 1