开发者

PHP header 404 not working

开发者 https://www.devze.com 2023-03-04 16:15 出处:网络
Why is this not working, as in the pre-set 404 page is not loaded: header(\"HTTP/1.0 404 N开发者_运维技巧ot Found\");

Why is this not working, as in the pre-set 404 page is not loaded:

header("HTTP/1.0 404 N开发者_运维技巧ot Found");
exit;

.htaccess has the ErrorDocument 404 /404.html directive set.

Thank you.


I unfortunately came across the same issue recently whilst working on a PHP project for work.

Sending a header is essentially only a 'status message', and doesn't make the browser or server show a particular page (although I believe some older versions of IE may show its default 404 page). This means that you will need to create your own 404 error message in your script, as the .htaccess error handling wont work.

My suggestion is to use something along the lines of

header("HTTP/1.0 404 Not Found");
include('./404.html');
exit;

I know it may seem stupid, but so far it's the only way I've found that will work.


Make sure your customized error page /404.html has the content size greater than 512 bytes. Many browsers like IE, Chrome etc don't show your customized page if content length of your custom 404 page is less than 512.

UPDATE

Based on your comments here is what I think is happening.

If you look at the access.log or http headers in Firebug/HTTP Watch etc of this blank page, you'd see a 404 return code. Once the web server starts processing the PHP page, it's already passed the point where it would handle 404 handling by itself since your php file is actually FOUND. Now since your php code is merely returning status 404 without any content therefore a blank page gets displayed.

Now since this is correct apache behavior and its up to you to create the contents for the 404 page. Something like this in your above php code will be fine I think:

<?php
header("HTTP/1.0 404 Not Found");
exit("<h1>Not Found</h1>
The requested URL " . $_SERVER["REQUEST_URI"] . " was not found on this server.
<hr>");
?>


This is mostly likely because Apache has already passed the initial request off to a PHP page to handle. Most likely because you have a front controller implementation in effect and are redirecting all web requests to this page. This leaves the responsibility of 404s to your application along with an appropriate 404 page to display.


I noticed that it does not work so I created a class with a static method to solve the problem

I have a directory /error-pages where I store all error file

I have a class file error.php which can be included at the top of every page

class ServerError{
    public static function show($page){
        require $_SERVER['DOCUMENT_ROOT'].'/error-pages/'.$page.'.php';
        exit();
    }
}

So on your home.php page for example you say

if (my404IsTrue) {
    ServerError::show("404");
}

this way. you can use it for any other kind of error be it 403 or a custom error

Hope it Helps

0

精彩评论

暂无评论...
验证码 换一张
取 消