PHP - Display a 404 Error without redirecting to another page
Asked Answered
E

6

15

I want to display a 404 Error if a user reaches a page that exists but I don't want him/her to see.

I don't want to do redirect (that would cause the address bar to show the link of the error page in the address bar) like the following:

if ($this_page_should_not_be_seen)
   header("Location: err.php?e=404");

Instead, it should seem like the page really doesn't exist, without having the URL in the browser's address changed.

Erde answered 21/6, 2012 at 11:57 Comment(6)
and what's wrong with htaccess?Veronicaveronika
That's the job for .htaccess, not for PHP file... or, for both of them, if you just redirect everything to index.php, but still, you need .htaccess or access to httpd.conf.Guano
you mean your browser shows the 404 error rather than a custom 404 page? you can redirect it to some page with doesn't exist in actual.Nanette
@Ummar That would work, but I was wondering if there is formal way to do this..Erde
best formal way I think is .htaccessNanette
okay... the actual thing is like this.. you have post.php for displaying posts. Your database has posts only upto 100. If any user queries post.php?id=101, at this case I need to show the 404 Not Found page..Erde
S
33

Include the error page in your current page and send a 404 error status code:

<?php
if ($nobody_should_ever_be_here) {
  header('HTTP/1.1 404 Not Found'); //This may be put inside err.php instead
  $_GET['e'] = 404; //Set the variable for the error code (you cannot have a
                    // querystring in an include directive).
  include 'err.php';
  exit; //Do not do any more work in this script.
}
?>

Note that this should be used if the page should never be seen. A better status code for un-authorized access (if the page should be seen by some logged in users) is 403 (Not Authorized).

Seep answered 21/6, 2012 at 11:59 Comment(1)
I came to realize this late but this is actually what I want.Erde
D
8

You can achieve a 404 (or any other HTTP response code really) programmatically with

header('HTTP/1.0 404 Not Found');
die;
Dotted answered 21/6, 2012 at 11:59 Comment(2)
@RajBD: It would always work if PHP runs as an Apache module (vs. running as FastCGI). Perhaps it doesn't do what you expect.Dotted
@DilipRajBaral It's working, but when you die() soon after header, you'll see empty output. When you're using php header 404 it will not automatically produce contents. You should add some contents before die() to make your custom 404 page. The header is used to tell search engines, spiders and bots the current url is not available anymore.Vega
V
4

In my experience the best way to show 404 error document without changing URL is to define error document in apaches .htaccess file:

RewriteEngine on
RewriteBase /

# Defines 404 error pages content:
ErrorDocument 404 /my_root/errors/404.html

# for all invalid links (non existing files):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* - [L,R=404]

# for some valid links (existing files to be un-accessible):
RewriteCond %{THE_REQUEST} ^.*some_file.php.*$ [NC]
RewriteRule .* - [L,R=404]
Vega answered 29/5, 2015 at 7:18 Comment(0)
T
1

What you write makes it hard to us to understand.

I want to redirect any incoming user to the 404 Error Page if s/he reaches the page I don't want him/her to reach.

So, a person reaches a page that exists?

If the person reaches for example a protected page that he/she is not supposted to see. Using header is the best way. Your options are to echo meta-refresh or javascript, but header is much cleaner. You could display something like You do not have permission to do that! which is pretty common on the web. If you don't want to redirect you could display a 404 "fake message" via the header.

If you are talking about someone reaching a 404 page, a file that does not exists, you only option is to use .htaccess

Trowel answered 21/6, 2012 at 12:2 Comment(1)
@Veronicaveronika There is .htaccess already being used for Error Page Handling. What I want to do is simply show the error page for existing page as it would have been shown for the non-existing page.Erde
K
1

may you can direct to your 404 page like

header('Location: http://www.website.com/errors/404.php');

Kazan answered 30/12, 2013 at 20:51 Comment(0)
C
0

These are all great answers for redirecting to 404 error, for a single page. Here's a solution that will allow you to test a condition and redirect for any script on your site.

Write up a .htaccess file, with the rewrite rules, and using [QSA,NC,L] to maintain the page location and the header post/get arguments...

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,NC,L]

This will cause every page to redirect to ./index.php (feel free to rename this if you're already using an index.php). The URL will not be changed. Then, in index.php, check some condition, and if passes, include the $_SERVER variable indicating the script, otherwise, do a custom 404. This means you can simply control the exception handling in index.php with...

$someNon404Condition = file_exists($_SERVER['PHP_SELF']);
if ($someNon404Condition) {
    include($_SERVER['PHP_SELF']);   // do the stuff
} else {
    print("404!  Why are you trying to access " . $_SERVER['PHP_SELF'] . "?");
}

This lets you do tons of other things, too! Forget a static 404.html page, with a dynamic one you can...

  • Your condition can be as complicated as you can code: check authentication, check for permanent redirects, maybe you want to expire content automatically? Etc., etc..
  • Search your DB for explode('/', $_SERVER['PHP_SELF']), and then display a list of those matched results under the header "Maybe this is what you were looking for?"
  • Respond to user-level events: Is it a 404 because the page was moved? Then handle a redirect. Is it a 404 because a moderator deleted it and it was the user's post? Tell the user a moderator deleted their post. Etc., etc..
  • Make API calls, dynamic code, etc., etc., the possibilities are there.
Cowpea answered 5/10, 2020 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.