Davey D
Davey D

Reputation: 460

404 error handling for a non-existing dynamic URL

Right now I got my .htaccess setup correctly:

ErrorDocument 404 /404.php

Whenever I access a non-existing page like mysite.com/g.php it gets redirected to the 404.php, header shows the 404 status.

Whenever somebody tries to access a story that doesn't exist, like mysite.com/story/123456 the 404 status is in the header, but no redirection to the 404 page.

I use this code whenever a story does not exist:

if ($result == 0) { header("HTTP/1.0 404 Not Found"); exit();}

What am I doing wrong?

Upvotes: 1

Views: 1417

Answers (3)

arkascha
arkascha

Reputation: 42915

This is the correct way to set a http response status:

<?php
// ...
if ($result == 0) { 
    http_response_code(404);
    exit();
}

Together with a ErrorDocument 404 /404.php in your http servers host configuration (or, if really necessary, in a dynamic configuration file (.htaccess)) that should do what you intend.

The corresponding documentation: http://php.net/manual/en/function.http-response-code.php

Upvotes: 0

Davey D
Davey D

Reputation: 460

Ok, I got a solution for the issue.

This code will give a 404 error and then I include the 404-page to show a page:

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

Upvotes: 1

Katie
Katie

Reputation: 2693

Give your error document the full path:

ErrorDocument 404 http://yourdomain.com/404.php

Upvotes: 2

Related Questions