How can I create an error 404 in PHP?

2019-01-03 14:16发布

My .htaccess redirects all requests to /word_here to /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.

If not, how can I simulate an error 404? I tried this, but it didn't result in my 404 page configured via ErrorDocument in the .htaccess showing up.

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

Am I right in thinking that it's wrong to redirect to my error 404 page?

7条回答
别忘想泡老子
2楼-- · 2019-01-03 14:44

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();
查看更多
爷、活的狠高调
3楼-- · 2019-01-03 14:46

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>
查看更多
叼着烟拽天下
4楼-- · 2019-01-03 14:51

Create custom error pages through .htaccess file

1. 404 - page not found

 RewriteEngine On
 ErrorDocument 404 /404.html

2. 500 - Internal Server Error

RewriteEngine On
ErrorDocument 500 /500.html

3. 403 - Forbidden

RewriteEngine On
ErrorDocument 403 /403.html

4. 400 - Bad request

RewriteEngine On
ErrorDocument 400 /400.html

5. 401 - Authorization Required

RewriteEngine On
ErrorDocument 401 /401.html

You can also redirect all error to single page. like

RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html
查看更多
混吃等死
5楼-- · 2019-01-03 14:51

try putting

ErrorDocument 404 /(root directory)/(error file) 

in .htaccess file.

Do this for any error but substitute 404 for your error.

查看更多
做个烂人
6楼-- · 2019-01-03 14:54

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don't continue the normal execution.

查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-03 14:54

What you're doing will work, and the browser will receive a 404 code. What it won't do is display the "not found" page that you might be expecting, e.g.:

Not Found

The requested URL /test.php was not found on this server.

That's because the web server doesn't send that page when PHP returns a 404 code (at least Apache doesn't). PHP is responsible for sending all its own output. So if you want a similar page, you'll have to send the HTML yourself, e.g.:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>

You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:

ErrorDocument 404 /notFound.php
查看更多
登录 后发表回答