Как вызвать ошибку 404 на сайте

My file .htaccess handles all requests from /word_here to my internal endpoint /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?

Valerio Bozz's user avatar

asked Sep 4, 2009 at 19:29

Eric's user avatar

2

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.

answered Jan 11, 2017 at 14:28

blade's user avatar

bladeblade

11.8k7 gold badges36 silver badges38 bronze badges

2

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

Kzqai's user avatar

Kzqai

22.5k25 gold badges105 silver badges135 bronze badges

answered Sep 4, 2009 at 19:50

JW.'s user avatar

JW.JW.

50.5k36 gold badges114 silver badges142 bronze badges

3

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

answered Sep 4, 2009 at 19:36

Ates Goral's user avatar

Ates GoralAtes Goral

137k26 gold badges137 silver badges190 bronze badges

2

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

answered Mar 30, 2016 at 10:34

Irshad Khan's user avatar

Irshad KhanIrshad Khan

5,6202 gold badges43 silver badges39 bronze badges

1

Did you remember to die() after sending the header? The 404 header doesn’t automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It’s not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your «what are you looking for?» page for the human reader.

answered Sep 4, 2009 at 19:50

Eli's user avatar

EliEli

97.1k20 gold badges76 silver badges81 bronze badges

Standard Apache 404 error looks like this:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>  

Thus, you can use the following PHP code to generate 404 page that looks exactly as standard apache 404 page:

function httpNotFound()
{
    http_response_code(404);
    header('Content-type: text/html');

    // Generate standard apache 404 error page
    echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>  
HTML;

    exit;
}

answered Mar 20 at 16:14

Dima L.'s user avatar

Dima L.Dima L.

3,39332 silver badges30 bronze badges

try putting

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

in .htaccess file.

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

StackedQ's user avatar

StackedQ

3,9791 gold badge27 silver badges41 bronze badges

answered May 20, 2018 at 19:41

the red crafteryt's user avatar

In the Drupal or WordPress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS’s 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

answered Jan 28, 2019 at 19:38

Mike Godin's user avatar

Mike GodinMike Godin

3,6363 gold badges27 silver badges29 bronze badges

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();

answered May 25, 2018 at 4:22

user5891645's user avatar

4

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

Nikos Hidalgo's user avatar

answered Mar 31, 2020 at 4:24

Mani Kandan's user avatar

1

MaxxxNSK

header("HTTP/1.0 404 Not Found");
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");

— не работает


  • Вопрос задан

    более трёх лет назад

  • 12829 просмотров

В помощь Вам http-response-code(404) клац
писать до любого вывода

Пригласить эксперта

Ставьте error_reporting(-1); в начале кода и смотрите что не так.
Скорее всего перед header() был вывод данных.
А может вы что-то не так поняли? Ваш код всего-лишь объявляет, что данная страница — страница ошибки. Чтобы именно вызвать 404 попробуйте exit(header('Location: /error404/'));

Попробуйте добавить exit(); сразу после вызова header();

Так-же перед вызовом header(); у Вас не должно быть вывода информации, если первый вариант не помог, попробуйте убрать закрывающий PHP тег ?> (если он есть)

На самом деле Вы всего лишь отправили заголовок, чтобы показать страницу нужно взять include или заголовок location.


  • Показать ещё
    Загружается…

04 июн. 2023, в 21:18

3000 руб./за проект

04 июн. 2023, в 20:31

10000 руб./за проект

04 июн. 2023, в 18:48

300 руб./за проект

Минуточку внимания

20.01.2021

Марат

33

0

php | header | 404 |

header 404. Как отправить на сервер заголовок header 404.
Ошибка отправки заголовка header 404. Все темы с примерами!

Всё о header(«HTTP/1.0 404 «)

  1. Код php заголовка 404
  2. Ошибка отправки header 404
  3. Для чего отправлять header 404, видео
  4. Пример отправки header 404
  5. Проверить попал ли в header 404
  6. Скачать можно здесь
  1. Код php заголовка 404

    Для того, чтобы отправить заголовок на сервер header 404 надо написать вот такую строчку:

    header(«HTTP/1.0 404 «);

    Естественно, что отправка 404 на сервер с помощью header должна осуществляться в самом верху страницы.

    ВНИМАНИЕ! ЭТО ВАЖНО!
    В самом верху страницы — это значит, что никакого, символа, ни точки, ни пробела ни переноса — вообще ничего, если у вас есть впереди php код, то код должен быть таким:

    <?

    здесь может быть сколько угодно кода php //

    НО! — никакого echo, print_r, var_dump и других выводящих функций!

    header(«HTTP/1.0 404 «);
    exit ;//

    используется в том случае, если требуется остановить выполнение ниже идущего кода.

    ?>

  2. Ошибка отправки header 404

    Если вы отправите заголовок header 404, как показано ниже, то вы получите ошибку отправки header 404:

    <?

    здесь код

    ?>

    <br> Привет мир

    <?

    header(«HTTP/1.0 404 «);

    ?>

    Пример ошибки отправки header 404:

    Если перед отправкой заголовка header 404 будет выводящий код, то получите ошибку.
    Давайте сделаем ошибку отправки header 404 специально!!
    Поместим какой-то текст произвольного содержания, перед отправкой header 404 :

    echo ‘Здесь текст, который выводится ранее, чем header 404’;

    header(«HTTP/1.0 404 «);

    Посмотрим это на скрине:
    Пример ошибки отправки header 404:

    Вывод ошибки отправки header 404

    Здесь текст, который выводится ранее, чем header 404

    Warning: Cannot modify header information — headers already sent by (output started at

    путь/page/php/header/001_header_404.html:3) in

    путь/page/php/header/001_header_404.html on line 4

    Вывод ошибки отправки header 404 на странице

    Вывод ошибки отправки header 404 на странице

  3. Для чего отправлять header 404

    Чтобы не гадать — по какой из причин вам может понадобится использовать отправку заголовка header 404 -приведу собственную причину использования header 404.
    На нашем сайте используется единая точка входа, — по всем запросам в адресной строке… будут перенаправляться на ту страницу, на которую настроена переадресация!

    И даже те, страницы, которые не существуют… все равно будут перенаправляться… на главную.

    Вот как раз для такого случая…

    Естественно, что ничего не понятно!

    Я делал специальное видео, где использовал приведенный код!

    Видео — использование header 404

    Друзья!

    Мне очень нужны подписчики!
    Пожалуйста подпишись на Дзене!
    Заранее спасибо!

  4. Пример отправки header 404

    Для того, чтобы разобраться в том, как работает отправка заголовка header 404 нам потребуется какая-то страница, которая не существует!

    Вообще любая!

    Например такая :

    У вас должна открыться такая страница 404 (несколько тем посвятили теме 404)
    Пример отправки header 404
    Но где здесь отправленный header 404 через php!? Этот скрин я вам привел специально — если вы захотите, то сделал отдельный архив -> сложил 404 через php + задний фон второй вариант 404 через php

    И теперь, чтобы увидеть, где заголовок надо -> нажимаем ctrl + U

    Нажмите, чтобы открыть в новом окне.

    Пример отправки header 404

  5. Проверить попал ли в header 404

    Как проверить правильно ли был отправлен заголовок с помощью header 404!?

    Если у вас возникли проблемы с пониманием того, что происходит заголовками, то существует огромное количество сайтов, которые могут показать всё, что вы отправляете!

    Выбрал первый попавший… https://bertal.ru/ — заходим на сайт в вставляем в адресную строку свой адрес страницы.

    Нажмите, чтобы открыть в новом окне.

    Проверить попал ли в header 404

P.S.

Вообще… после случая с санкциями… пошел посмотреть, а что вообще творится со страницами на моем другом сайте и обнаружил, что робот проиндексировал папки(директории) – как отдельные страницы – и описанная тема… как раз востребована была там.

Не благодарите, но ссылкой можете поделиться!

Название скрипта :php header 404

COMMENTS+

 
BBcode


In this tutorial, we are going to show you how to send a “404 Not Found” header using PHP.

This can be especially useful in cases when you need to display a 404 message if a particular database record does not exist.

By sending a 404 HTTP status code to the client, we can tell search engines and other crawlers that the resource does not exist.

To send a 404 to the client, we can use PHP’s http_response_code function like so.

//Send 404 response to client.
http_response_code(404)
//Include custom 404.php message
include 'error/404.php';
//Kill the script.
exit;

Note that this function is only available in PHP version 5.4 and after.

If you are using a PHP version that is older than 5.4, then you will need to use the header function instead.

//Use header function to send a 404
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
//Include custom message.
include 'errors/404.php';
//End the script
exit;

In the code above, we.

  1. Send the response code to the client.
  2. We include a PHP file that contains our custom “404 Not Found” error. This file is not mandatory, so feel free to remove it if you want to.
  3. We then terminated the PHP script by calling the exit statement.

If you run one of the code samples above and check the response in your browser’s developer tools, then you will see something like this.

Request URL:http://localhost/test.php
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade

Note the Status Code segment of the server’s HTTP response. This is the 404 header.

When should I use this?

In most cases, your web server will automatically handle 404 errors if a resource does not exist.

However, what happens if your script is dynamic and it selects data from your database? What if you have a dynamic page such as users.php?id=234 and user 234 does not exist?

The file users.php will exist, so your web server will send back a status of “200 OK”, regardless of whether a user with the ID 234 exists or not.

In cases like this, we may need to manually send a 404 Not Found header.

Why isn’t PHP showing the same 404 message as my web server?

You might notice that your web server does not serve its default “404 Not Found” error message when you manually send the header with PHP.

404 Not Found

The default message that Apache displays whenever a resource could not be found.

This is because, as far as the web server is concerned, the file does exist and it has already done its job.

One solution to this problem is to make sure that PHP and your web server display the exact same 404 message.

For example, with Apache, you can specify the path of a custom error message by using the ErrorDocument directive.

ErrorDocument 404 /errors/404.php

The Nginx web server also allows you to configure custom error messages.

  • What is 404 or Page not Found Error?
  • Why is Custom 404 Error Page Needed?
  • Let’s Start — Create Custom 404 Error Page
  • Put the Custom 404 Error Page into ROOT Directory of Your Website
  • Create/Modify the .htaccess File
  • Testing the 404 Error Document
  • Does Custom 404 Error Page Return 200 OK or 302 response?

What is 404 or Page not Found Error?

Before creating a custom 404 page not found error page we should understand what is 404 page not found error code? The 404 code is a standard HTTP response code that tells the client browser that the server is communicable but could not find the requested resource. When the requested resource is not found on the server then server sends a 404 code in response of the client’s request. This is also called page not found error. A 404 response simply means the server has not found anything matching the Request-URI. It does not indicate if the requested resource is unavailable temporarily or permanently. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

Why is Custom 404 Error Page Needed?

User is shown a 404 error page when he/she tries to access a non-existent page on a site that has either been moved or deleted or user has mistyped a URL. A 404 error page is just an information for the user that the page requested by him/her is not available. This is site owner’s responsibility to return a meaningful and well formatted 404 error page so that surfer gets useful information when the requested page is not available.

Let’s Start — Create Custom 404 Error Page

To create a PHP version of custom 404 error page open any text editor of your choice and insert the following code and save it as 404page.php or any other name of your choice but the extension must be .php because here 404 error page is being demonstrated with PHP technology.

<?php
  header("HTTP/1.0 404 Not Found");
?>
<html>
  <head>
    <title>404 Error - Page Not Found</title>
  </head>
  <body>404 Error - Page Not Found!</body>
</html>

Following things you must remember while creating a 404 error page.

  • You must specify the 404 HTTP response header in your custom 404 error page else it would be treated as a normal page and 200 OK response will be sent to client browser.
  • The header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. In above sample error page the header that starts with the string «HTTP/» (case is not significant) will be used to figure out the HTTP status code to send. Here we have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive — will be explained shortly), we make sure that our script generates the proper status code.

The above page is just for demonstration, you can beautify your custom 404 error page as you like and add more relevant content depending upon how much information you want to convey to your audience.

Put the Custom 404 Error Page into ROOT Directory of Your Website

After having created a custom 404 error page you have to put this page into home or ROOT directory of your website. To do that connect to your website by ftp client or some file manager tool and upload the error page there.

Create/Modify the .htaccess File

Those who are beginners the .htaccess file is a file found in Apache servers that allows you to manipulate the behaviour of the server. A very common use of .htaccess is to create custom error messages for server errors. This article configures error page on Apache web server. If your web host is not running on Apache then this solution may not work for you; and in that situation you will have to find out from your web host what you need to do to enable the server to serve your customized file when a web page is not found.

If your website running Apache web server, the first thing you need to do is to add the following line to a file named .htaccess (note the preceding period). In most instances, no such file will exist, and you can simply create one with a text editor (such as Notepad on Windows). Incidentally, if you are using Notepad on Windows, you will need to enter «.htaccess» (including the opening and closing quotation marks) into the «Save As» dialog box when you create the file, otherwise Notepad will append a «.txt» extension behind your back when it creates the file. And unless you configured Windows to show you the full filename, you won’t even realise that it has done so.

ErrorDocument 404 /404page.php

Now, upload your .htaccess to the root directory of your website. By doing above steps you are done with 404 error page and this is the time to test the error page.

Testing the 404 Error Document

Test your 404 error page by typing a URL that you know does not exist. Your error page should load up. Remember the domain name must be correct followed by a wrong page name. If domain name is not correct the request won’t reach to your website.

For the custom 404 error page you must check if that returns a correct 404 response. If your page still returns 200 OK or 302 response code then something wrong there and your page won’t serve the purpose it was designed for. Chrome’s inspect element and Firefox’s firebug extension may help you in checking response headers for your error page.

Does Custom 404 Error Page Return 200 OK or 302 response?

For custom 404 error page, the path given in .htaccess must be relative to ROOT directory else your page will return a 200 OK response, which will of course won’t serve the desired purpose. This fact applies to almost all servers including both Apache and IIS. For example, see the following entries and accommodate the correct one in your .htaccess file. The second one having absolute URL for error document will return 200 OK response.

ErrorDocument 404 /404page.php        #Correct implementation of error page

ErrorDocument 404 http://cs-fundamentals.com/404page.php     #WRONG! Results in 200 OK

Last Word

Hope you have enjoyed reading this tutorial on creating custom 404 page not found error page. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

Понравилась статья? Поделить с друзьями:
  • Как вызвать ошибку 404 django
  • Как вызвать ошибку 403
  • Как вызвать звук ошибки windows
  • Как вызвать журнал ошибок
  • Как вызвать 400 ошибку