开发者

PHP Redirect Headers Best Practices

I'm creating a PHP CMS and have some system pages like a 404 page, a maintenance page, an开发者_运维百科d an unauthorized access page. When Page A isn't found, the CMS will redirect to the 404 page; if the user doesn't have access to Page B, it will redirect to the unauthorized access page, etc.

I'd like to use the proper status code in the header of each page, but I need clarification on how to handle the header/redirect. Do I put the 404 header on Page A and then redirect to the 404 page or do I put the 404 status on the 404 page itself? Also, if the latter is the correct answer, what kind of redirect should I use to get there, a 301 or a 302?


If a user arrives on page A and that page doesn't exist, then do not redirect : just send a 404 error code from page A -- and, to be nice for your user, an HTML content indicating that the page doesn't exist.

This way, the browser (and it's even more true for crawlers ! ) will know that the page that is not found is page A, and not anything else you'd have tried to redirect to.

Same for other kind of errors, btw : if a specific URL corresponds to an error, then, the error code should be sent from that URL.


Basically, something as simple as this should be enough :

if (page not found) {
    header("404 Not Found");
    echo "some nice message that says the page doesn't exist";
    die;
}

(Well, you could output something nicer, of course ; but you get the idea ;-) )


I'm not sure if the redirecting is the best way for doing this. Id rather use some built in functionality that is included into the project.

If the data is not found, do not redirect the user to another page, just send him an error message, like Hey, this site does not exists! Try an other one and so. And not at the end, you should build into the code, the code-part from the answer of Pascal Martin.

I would do this into a function, and call it from a bootstrap or something with a similar behavior.

function show_error($type="404", $header = true, $die = false)
{
    if($header)
        header("404 Not Found");

    echo file_get_contents($type.'.php');

    if($die) die; //
    // and so on...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜