Меню

Как вывести ошибку 404 php

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

http_response_codeПолучает или устанавливает код ответа HTTP

Описание

http_response_code(int $response_code = 0): int|bool

Список параметров

response_code

Код ответа устанавливается с помощью опционального параметра response_code.

Возвращаемые значения

Если response_code задан, то будет возвращён предыдущий код
статуса. Если response_code не задан, то будет возвращён
текущий код статуса. Оба этих значения будут по умолчанию иметь код состояния 200,
если они используются в окружении веб-сервера.

Если response_code не задан и используется не в окружении
веб-сервера (например, в CLI), то будет возвращено false. Если
response_code задан и используется не в окружении
веб-сервера, то будет возвращено true (но только если не был установлен предыдущий
код статуса).

Примеры

Пример #1 Использование http_response_code() в окружении веб-сервера


<?php// Берём текущий код и устанавливаем новый
var_dump(http_response_code(404));// Берём новый код
var_dump(http_response_code());
?>

Результат выполнения данного примера:

Пример #2 Использование http_response_code() в CLI


<?php// Берём текущий код по умолчанию
var_dump(http_response_code());// Устанавливаем код
var_dump(http_response_code(201));// Берём новый код
var_dump(http_response_code());
?>

Результат выполнения данного примера:

bool(false)
bool(true)
int(201)

Смотрите также

  • header() — Отправка HTTP-заголовка
  • headers_list() — Возвращает список переданных заголовков (или готовых к отправке)

craig at craigfrancis dot co dot uk

11 years ago


If your version of PHP does not include this function:

<?phpif (!function_exists('http_response_code')) {
        function
http_response_code($code = NULL) {

            if (

$code !== NULL) {

                switch (

$code) {
                    case
100: $text = 'Continue'; break;
                    case
101: $text = 'Switching Protocols'; break;
                    case
200: $text = 'OK'; break;
                    case
201: $text = 'Created'; break;
                    case
202: $text = 'Accepted'; break;
                    case
203: $text = 'Non-Authoritative Information'; break;
                    case
204: $text = 'No Content'; break;
                    case
205: $text = 'Reset Content'; break;
                    case
206: $text = 'Partial Content'; break;
                    case
300: $text = 'Multiple Choices'; break;
                    case
301: $text = 'Moved Permanently'; break;
                    case
302: $text = 'Moved Temporarily'; break;
                    case
303: $text = 'See Other'; break;
                    case
304: $text = 'Not Modified'; break;
                    case
305: $text = 'Use Proxy'; break;
                    case
400: $text = 'Bad Request'; break;
                    case
401: $text = 'Unauthorized'; break;
                    case
402: $text = 'Payment Required'; break;
                    case
403: $text = 'Forbidden'; break;
                    case
404: $text = 'Not Found'; break;
                    case
405: $text = 'Method Not Allowed'; break;
                    case
406: $text = 'Not Acceptable'; break;
                    case
407: $text = 'Proxy Authentication Required'; break;
                    case
408: $text = 'Request Time-out'; break;
                    case
409: $text = 'Conflict'; break;
                    case
410: $text = 'Gone'; break;
                    case
411: $text = 'Length Required'; break;
                    case
412: $text = 'Precondition Failed'; break;
                    case
413: $text = 'Request Entity Too Large'; break;
                    case
414: $text = 'Request-URI Too Large'; break;
                    case
415: $text = 'Unsupported Media Type'; break;
                    case
500: $text = 'Internal Server Error'; break;
                    case
501: $text = 'Not Implemented'; break;
                    case
502: $text = 'Bad Gateway'; break;
                    case
503: $text = 'Service Unavailable'; break;
                    case
504: $text = 'Gateway Time-out'; break;
                    case
505: $text = 'HTTP Version not supported'; break;
                    default:
                        exit(
'Unknown http status code "' . htmlentities($code) . '"');
                    break;
                }
$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');header($protocol . ' ' . $code . ' ' . $text);$GLOBALS['http_response_code'] = $code;

            } else {

$code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

            }

            return

$code;

        }
    }

?>

In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:

https://bugs.php.net/bug.php?id=52555

For reference the error codes I got from PHP's source code:

http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354

And how the current http header is sent, with the variables it uses:

http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856


Stefan W

8 years ago


Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).

The following codes currently work as expected (with PHP running as Apache module):
200 – 208, 226
300 – 305, 307, 308
400 – 417, 422 – 424, 426, 428 – 429, 431
500 – 508, 510 – 511

Codes 0, 100, 101, and 102 will be sent as "200 OK".

Everything else will result in "500 Internal Server Error".

If you want to send responses with a freestyle status line, you need to use the `header()` function:

<?php header("HTTP/1.0 418 I'm A Teapot"); ?>


Thomas A. P.

7 years ago


When setting the response code to non-standard ones like 420, Apache outputs 500 Internal Server Error.

This happens when using header(0,0,420) and http_response_code(420).
Use header('HTTP/1.1 420 Enhance Your Calm') instead.

Note that the response code in the string IS interpreted and used in the access log and output via http_response_code().


Anonymous

9 years ago


Status codes as an array:

<?php
$http_status_codes
= array(100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 306 => "(Unused)", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-URI Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 419 => "Authentication Timeout", 420 => "Enhance Your Calm", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 424 => "Method Failure", 425 => "Unordered Collection", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 444 => "No Response", 449 => "Retry With", 450 => "Blocked by Windows Parental Controls", 451 => "Unavailable For Legal Reasons", 494 => "Request Header Too Large", 495 => "Cert Error", 496 => "No Cert", 497 => "HTTP to HTTPS", 499 => "Client Closed Request", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required", 598 => "Network read timeout error", 599 => "Network connect timeout error");
?>

Source: Wikipedia "List_of_HTTP_status_codes"


viaujoc at videotron dot ca

2 years ago


Do not mix the use of http_response_code() and manually setting  the response code header because the actual HTTP status code being returned by the web server may not end up as expected. http_response_code() does not work if the response code has previously been set using the header() function. Example:

<?php
header
('HTTP/1.1 401 Unauthorized');
http_response_code(403);
print(
http_response_code());
?>

The raw HTTP response will be (notice the actual status code on the first line does not match the printed http_response_code in the body):

HTTP/1.1 401 Unauthorized
Date: Tue, 24 Nov 2020 13:49:08 GMT
Server: Apache
Connection: Upgrade, Keep-Alive
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

403

I only tested it on Apache. I am not sure if this behavior is specific to Apache or common to all PHP distributions.


Anonymous

8 years ago


You can also create a enum by extending the SplEnum class.
<?php/** HTTP status codes */
class HttpStatusCode extends SplEnum {
    const
__default = self::OK;

        const

SWITCHING_PROTOCOLS = 101;
    const
OK = 200;
    const
CREATED = 201;
    const
ACCEPTED = 202;
    const
NONAUTHORITATIVE_INFORMATION = 203;
    const
NO_CONTENT = 204;
    const
RESET_CONTENT = 205;
    const
PARTIAL_CONTENT = 206;
    const
MULTIPLE_CHOICES = 300;
    const
MOVED_PERMANENTLY = 301;
    const
MOVED_TEMPORARILY = 302;
    const
SEE_OTHER = 303;
    const
NOT_MODIFIED = 304;
    const
USE_PROXY = 305;
    const
BAD_REQUEST = 400;
    const
UNAUTHORIZED = 401;
    const
PAYMENT_REQUIRED = 402;
    const
FORBIDDEN = 403;
    const
NOT_FOUND = 404;
    const
METHOD_NOT_ALLOWED = 405;
    const
NOT_ACCEPTABLE = 406;
    const
PROXY_AUTHENTICATION_REQUIRED = 407;
    const
REQUEST_TIMEOUT = 408;
    const
CONFLICT = 408;
    const
GONE = 410;
    const
LENGTH_REQUIRED = 411;
    const
PRECONDITION_FAILED = 412;
    const
REQUEST_ENTITY_TOO_LARGE = 413;
    const
REQUESTURI_TOO_LARGE = 414;
    const
UNSUPPORTED_MEDIA_TYPE = 415;
    const
REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const
EXPECTATION_FAILED = 417;
    const
IM_A_TEAPOT = 418;
    const
INTERNAL_SERVER_ERROR = 500;
    const
NOT_IMPLEMENTED = 501;
    const
BAD_GATEWAY = 502;
    const
SERVICE_UNAVAILABLE = 503;
    const
GATEWAY_TIMEOUT = 504;
    const
HTTP_VERSION_NOT_SUPPORTED = 505;
}


divinity76 at gmail dot com

2 years ago


if you need a response code not supported by http_response_code(), such as WebDAV / RFC4918's "HTTP 507 Insufficient Storage", try:

<?php
header
($_SERVER['SERVER_PROTOCOL'] . ' 507 Insufficient Storage');
?>
result: something like

HTTP/1.1 507 Insufficient Storage


Rob Zazueta

9 years ago


The note above from "Anonymous" is wrong. I'm running this behind the AWS Elastic Loadbalancer and trying the header(':'.$error_code...) method mentioned above is treated as invalid HTTP.

The documentation for the header() function has the right way to implement this if you're still on < php 5.4:

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


Anonymous

10 years ago


If you don't have PHP 5.4 and want to change the returned status code, you can simply write:
<?php
header
(':', true, $statusCode);
?>

The ':' are mandatory, or it won't work

Steven

7 years ago


http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method.

In summary - The differences between "http_response_code" and "header" for setting response codes:

1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.

2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.


Richard F.

9 years ago


At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.

<?php// HTTP/1.1 404 Not Found
http_response_code(404);?>

The resulting response is HTTP/1.1 404 OK


stephen at bobs-bits dot com

8 years ago


It's not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
<?php

$a

= http_response_code();
$b = http_response_code(202);
$c = http_response_code();var_dump($a, $b, $c);// Result:
// int(200)
// int(200)
// int(202)
?>

Chandra Nakka

5 years ago


On PHP 5.3 version, If you want to set HTTP response code. You can try this type of below trick :)

<?php

header

('Temporary-Header: True', true, 404);
header_remove('Temporary-Header');?>


yefremov {dot} sasha () gmail {dot} com

8 years ago


@craig at craigfrancis dot co dot uk@ wrote the function that replaces the original. It is very usefull, but has a bug. The original http_response_code always returns the previous or current code, not the code you are setting now. Here is my fixed version. I also use $GLOBALS to store the current code, but trigger_error() instead of exit. So now, how the function will behave in the case of error lies on the error handler. Or you can change it back to exit().

if (!function_exists('http_response_code')) {
    function http_response_code($code = NULL) {    
        $prev_code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

        if ($code === NULL) {
            return $prev_code;
        }

        switch ($code) {
            case 100: $text = 'Continue'; break;
            case 101: $text = 'Switching Protocols'; break;
            case 200: $text = 'OK'; break;
            case 201: $text = 'Created'; break;
            case 202: $text = 'Accepted'; break;
            case 203: $text = 'Non-Authoritative Information'; break;
            case 204: $text = 'No Content'; break;
            case 205: $text = 'Reset Content'; break;
            case 206: $text = 'Partial Content'; break;
            case 300: $text = 'Multiple Choices'; break;
            case 301: $text = 'Moved Permanently'; break;
            case 302: $text = 'Moved Temporarily'; break;
            case 303: $text = 'See Other'; break;
            case 304: $text = 'Not Modified'; break;
            case 305: $text = 'Use Proxy'; break;
            case 400: $text = 'Bad Request'; break;
            case 401: $text = 'Unauthorized'; break;
            case 402: $text = 'Payment Required'; break;
            case 403: $text = 'Forbidden'; break;
            case 404: $text = 'Not Found'; break;
            case 405: $text = 'Method Not Allowed'; break;
            case 406: $text = 'Not Acceptable'; break;
            case 407: $text = 'Proxy Authentication Required'; break;
            case 408: $text = 'Request Time-out'; break;
            case 409: $text = 'Conflict'; break;
            case 410: $text = 'Gone'; break;
            case 411: $text = 'Length Required'; break;
            case 412: $text = 'Precondition Failed'; break;
            case 413: $text = 'Request Entity Too Large'; break;
            case 414: $text = 'Request-URI Too Large'; break;
            case 415: $text = 'Unsupported Media Type'; break;
            case 500: $text = 'Internal Server Error'; break;
            case 501: $text = 'Not Implemented'; break;
            case 502: $text = 'Bad Gateway'; break;
            case 503: $text = 'Service Unavailable'; break;
            case 504: $text = 'Gateway Time-out'; break;
            case 505: $text = 'HTTP Version not supported'; break;
            default:
                trigger_error('Unknown http status code ' . $code, E_USER_ERROR); // exit('Unknown http status code "' . htmlentities($code) . '"');
                return $prev_code;
        }

        $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
        header($protocol . ' ' . $code . ' ' . $text);
        $GLOBALS['http_response_code'] = $code;

        // original function always returns the previous or current code
        return $prev_code;
    }
}


Anonymous

4 years ago


http_response_code() does not actually send HTTP headers, it only prepares the header list to be sent later on.
So you can call http_reponse_code() to set, get and reset the HTTP response code before it gets sent.

Test code:
<php
http_response_code(500);  // set the code
var_dump(headers_sent());  // check if headers are sent
http_response_code(200);  // avoid a default browser page


Kubo2

6 years ago


If you want to set a HTTP response code without the need of specifying a protocol version, you can actually do it without http_response_code():

<?php

header

('Status: 404', TRUE, 404);?>


zweibieren at yahoo dot com

7 years ago


The limited list given by Stefan W is out of date. I have just tested 301 and 302 and both work.

divinity76 at gmail dot com

6 years ago


warning, it does not check if headers are already sent (if it is, it won't *actually* change the code, but a subsequent call will imply that it did!!),

you might wanna do something like
function ehttp_response_code(int $response_code = NULL): int {
    if ($response_code === NULL) {
        return http_response_code();
    }
    if (headers_sent()) {
        throw new Exception('tried to change http response code after sending headers!');
    }
    return http_response_code($response_code);
}


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.3k7 gold badges36 silver badges37 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.4k24 gold badges104 silver badges134 bronze badges

answered Sep 4, 2009 at 19:50

JW.'s user avatar

JW.JW.

50.1k36 gold badges114 silver badges141 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

136k26 gold badges135 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,5162 gold badges42 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

96.3k20 gold badges75 silver badges81 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,9011 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,5663 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

Ошибка 404Я решил перенести большую часть файлов со старого сайта на новый. И у меня возник вопрос — «А не обвинит ли меня Yandex в использовании неуникальных статей?», т.к. у меня одни и те же материалы будут на разных страницах.

Я написал письмо в службу поддержки yandex, и мне пришло письмо, в котором сообщалось, что переживать не надо. Единственно, настоятельно желательно, чтобы я каким-то способом закрыл старые странички от индексирования (через robots.txt, вызов ошибки 404 или перенаправление) и удалил странички из базы по адресу http://webmaster.yandex.ru/delurl.xml. Удалять по указанному адресу желательно, чтобы быстрее прекратилась индексация страниц.

По некоторым причинам я предпочел способ вызова ошибки 404. Ошибка 404 вызывается в том случае, если ресурс на который идет ссылка не обнаружен. И тут я обнаружил, что у меня то и нет вызова этой ошибки, т.е. какие бы данные пользователь не ввел бы на старом сайте, что-то все равно выводится. Такая ситуация на мой взгляд не допустима, и я пошел с ней бороться.

Мой сайт написан был на php, поэтому я очень быстро нашел команду для вызова ошибки 404. Она имеет вид:

header("HTTP/1.0 404 Not Found");
exit;

Казалось бы все просто, но нет же. Никак эти две команды не хотели работать. Тогда я почитал дополнительно материал и выяснил, что  header() должна вызываться до отправки любого другого вывода. Т.е. она должна быть исключительно самой первой при выводе, поэтому ее нельзя использовать внутри require_once().

Но как оказалось существуют три замечательные функции, которые позволяют решить эту проблему:

  • ob_start() — задает начало области, которую надо поместить в буфер, я поместил ее самой первой при выводе.

  • ob_end_flush() — окончание задания буфер и сразу вывод. Т.е. первые две функции задают область, которую сначала нужно вывести в буфер, а потом сразу вывести.
  • ob_end_clean() — очищает буфер, и следующая команда как бы выводится самой первой.

С использованием этих команд организация вызова ошибки 404 выглядит следующим образом:

  1. Самая первая команда — ob_start()
  2. Далее идет основное содержание, которое пока копируется в буфер.
  3. Проверка на предмет вызова ошибки 404. Например, проверка наличия определенного значения. Если после проверки имеются причины вызвать ошибку, то задается код:
    ob_end_clean() ;
    header("HTTP/1.0 404 Not Found");
    exit;

    Тем самым будет выдано сообщение об ошибке и осуществлен выход.

  4. Выводим содержимое буфера командой ob_end_flush(). Идея в том, что если была вызвана ошибка, то сюда не попадем. Если ошибки не было, то выводим буфер.

Далее в файле .htaccess можно указать файл, который будет сопоставляться ошибке 404, но это уже совершенно другая история…

20.01.2021

Марат

1729

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


Website error pages are perhaps one of the most overlooked pieces of a fully rounded website. Not only are they important but they give you the opportunity to have a little fun. Although many web developers rely on server logs to keep an eye out for hits on error pages, I’m going to take a different approach by using a PHP generated email. In addition, we will spice up the design a bit, add basic navigation and link to the website sitemap.

About Error Pages

404 Not Found404 Not Found404 Not Found

The most common error page — the one in which you are most likely to be familiar with — is the «404 Not Found page». More people encounter this type of error page than any other. Other common error messages you may have come across are 500 Internal Server Error, 400 Bad Request or 403 Forbidden. Wondering what the number is for? It simply refers to the HTTP code.

404 Not Found404 Not Found404 Not Found

Default error pages are quite boring (as you can see above) and offer no purpose to visitors other than letting them know some boring error happened. For these reasons, it is a great idea to provide custom pages for the most common errors encountered. This tutorial will only cover two: the «404 Not Found» and «403 Forbidden».

Check for custom error page support

First, check to make sure your hosting provider allows you to use your own error pages. Almost all of them do, and most of them even provide a configuration area within your control panel to help you quickly create the pages. In this tutorial we will configure an Apache web server (the most common). This is easier than you might think.

Configure .htaccess

Next, connect to your server via FTP or control panel and navigate to the document root directory (usually www or public_html) which contains your website files. We will be looking for the .htaccess file. It is sometimes hidden so make sure you are viewing all files including hidden ones. If your server doesn’t have one, you can create one using any text editor. Make sure to make a backup of the .htaccess file if your server already has one.

Add the following lines to your .htaccess file:

1
ErrorDocument 404 /error/404.php
2
ErrorDocument 403 /error/403.php

The first half (ErrorDocument 404) is telling the server we are going to define the location of the 404 error document. The second half defines the actual location of the error document. In this case we will put it in the «error» directory and call them 404.php and 403.php, respectively.

Now save the .htaccess file and upload it to the document root directory.

Design the Custom Error Pages

It is best to stay with the same design as your website already uses so that you don’t confuse your visitors and risk losing them. You should also include helpful elements such as a polite error message, suggested links, a search feature, or a link to your sitemap. These features will depend on the level of content your website provides and what you feel will be most helpful.

Envato Marketplace 404 PageEnvato Marketplace 404 PageEnvato Marketplace 404 Page

As you can see below, the 404 Not Found page for Nettuts+ has stated the error and emphasized the search feature by including it in the body beneath the error message. You could take this a step further by including a short list of links to possible pages which might encourage the visitor to continue exploring more of the site (keep it simple and short though) -or even a humorous image (every one likes laughing right?). For small websites it may be a good idea to include a visible sitemap as well.

Page Not FoundPage Not FoundPage Not Found

Here is something I put together for this tutorial that you can use for your website as well (included in the download above). It’s very simple so you will be able to put the content of it directly into your existing website template. As you can see, I attempted to include a little bit of a humorous element while also stating the error politely and including some options to help the visitor either find what they were looking for or continue browsing the website.

404 Not Found404 Not Found404 Not Found

You’ll notice it does not specify the HTTP error code in the body of the page. Instead I chose to only use the error code in the title of the page. The reason for this is to keep things as simple and user friendly as possible. Most people don’t care what 404 or 403 means, they want to know what’s going on in plain English. For people who want the error code, it is still available via the title.

If you want to see some really great 404 designs visit:

  • http://www.smashingmagazine.com/2009/01/29/404-error-pages-reloaded-2/
  • http://www.smashingmagazine.com/2007/08/17/404-error-pages-reloaded/
  • http://www.smashingmagazine.com/2007/07/25/wanted-your-404-error-pages/
  • http://blogof.francescomugnai.com/2008/08/the-100-most-funny-and-unusual-404-error-pages/

The Auto-Mailer PHP and Why We Will Use Email Notification

This is the part of the tutorial in which some web guru’s might argue with. You can use your web server’s logs to check for error pages and much, much more. Why do I choose email notifications?

  1. I don’t want to log into my server every day and dig through all that extra information.
  2. I am available by email almost literally all day, the fastest way to reach me is email (or twitter). With this in mind, I want to know about 404 and 403 errors fairly quick so email is best.
  3. An increasing number of people are starting websites, while most of those people know almost nothing about web hosting let alone server logs. These people will only be running small sites; so email is ideal.
  4. Being notified right away allows me to quickly take action if a website of mine is being «harvested» (ThemeForest templates), if someone is attempting to access something restricted repeatedly or if I have a broken link somewhere.

So with all that said, let’s get on with the code shall we!

The Code

First, we will create a file named error-mailer.php which will be used to collect information about our visitor and send the email. Once you have created the file we will start by specifying our email and email settings.

1
<?php
2

3
# The email address to send to

4
	$to_email = 'YOUR-EMAIL@DOMAIN.com';
5

6
# The subject of the email, currently set as 404 Not Found Error or 403 Forbidden Error

7
	$email_subject = $error_code.' Error';
8

9
# The email address you want the error to appear from

10
	$from_email = 'FROM-EMAIL@DOMAIN.COM';
11

12
# Who or where you want the error to appear from

13
	$from_name = 'YourDomainName.com';

Then we will collect information about our visitor such as IP address, requested URI, User Agent, etc. The following code will collect that information.

1
# Gather visitor information

2
    $ip = getenv ("REMOTE_ADDR");                // IP Address

3
    $server_name = getenv ("SERVER_NAME");       // Server Name

4
    $request_uri = getenv ("REQUEST_URI");       // Requested URI

5
    $http_ref = getenv ("HTTP_REFERER");         // HTTP Referer

6
    $http_agent = getenv ("HTTP_USER_AGENT");    // User Agent

7
    $error_date = date("D M j Y g:i:s a T");     // Error Date

Now we will write the script to email the information to us with the details specified earlier.

1
# Send the email notification

2
require_once('phpMailer/class.phpmailer.php');
3
    $mail = new PHPMailer();
4

5
    $mail->From = $from_email;
6
    $mail->FromName = $from_name;
7
    $mail->Subject = $email_subject;
8
    $mail->AddAddress($to_email);
9
    $mail->Body =
10
    "There was a ".$error_code." error on the ".$server_name." domain".
11
    "nnDetailsn----------------------------------------------------------------------".
12
    "nWhen: ".$error_date.
13
    "n(Who) IP Address: ".$ip.
14
    "n(What) Tried to Access: http://".$server_name.$request_uri.
15
    "n(From where) HTTP Referer: ".$http_ref.
16
    "nnUser Agent: ".$http_agent;
17

18
    $mail->Send();
19

20
?>

We are using the phpMailer class to do this as demonstrated by Jeffrey via the ThemeForest blog to create a nice AJAX contact form. This version of the phpMailer class is for PHP 5/6 so if your server is running PHP 4 you will need to use the corresponding version by downloading it here.

404.php and 403.php Error Pages

The last thing we need to do is customize the error pages we designed earlier by sending the proper headers and set the $error_code variable by inserting the following code at the beginning of each page respectively (separated by ——-).

1
<?php 
2

3
header("HTTP/1.0 404 Not Found");
4
$error_code = '404 Not Found';		// Specify the error code

5
require_once('error-mailer.php');	// Include the error mailer script

6

7
?>
8
-------
9
<?php 
10

11
header("HTTP/1.0 403 Forbidden");
12
$error_code = '403 Forbidden';		// Specify the error code

13
require_once('error-mailer.php');	// Include the error mailer script

14

15
?>

What we are doing here first is setting the correct HTTP header to return 404 Not Found and 403 Forbidden, respectively. When search engines accidentally land on this page we want to make sure they know what kind of page it is, instead of thinking that it’s a normal web page named 404.php or 403.php.

Then we specify the error code to be used in the mailer script and include the mailer script so it can do its work. This way if we make a change to the mailer script, we only need to edit one file instead of two or more (if you setup additional custom error pages).

Conclusion

There you have it! Your own custom error pages that are search engine friendly, and let you know via email when you’ve had a visitor as well as all the information you will need to fix any problems. A few last things to consider:

  1. Internet Explorer requires error pages that are at least 512 byes in size (if you use the example files you’ll be fine)
  2. High traffic websites have the potential to generate A LOT of emails so make sure you setup some sort of email filter for these error notifications so they don’t flood your inbox. I use Gmail so I just have a label and filter setup for these emails.

Did you find this post useful?

Jarel Remick

I’m a freelance designer and web developer, an author and reviewer at ThemeForest.net, a writer for the ThemeForest blog and occasionally net.tutsplus.com. When I actually manage to get away from the computer, I’m hiking, watching movies or spending time with my girlfriend in sunny Las Vegas. – View my web.appstorm.net posts here.

Если пользователь вобьет в адресную строку
некорректный URL мы должны показать страницу
с ошибкой. Пусть контент страницы с ошибкой
будет хранится в соответствующем файле:

<div>
page not found
</div>

Для того, чтобы определить некорректность
запроса, нам необходимо проверить существование
файла контента, соответствующего запрошенному URL:

<?php
$path = 'view' . $url . '.php';

if (file_exists($path)) {
// файл есть
} else {
// файла нет
}
?>

Давайте будем отдавать файл контента, если
он есть, и файл с ошибкой, если контента нет:

<?php
$path = 'view' . $url . '.php';

if (file_exists($path)) {
$content = file_get_contents($path);
} else {
$content = file_get_contents('view/404.php');
}
?>

В случае с ошибкой мы должны отправить в
браузер заголовок с 404 ошибкой, чтобы
явно сообщить о том, что страница не найдена.
Сделаем это:

<?php
$path = 'view' . $url . '.php';

if (file_exists($path)) {
$content = file_get_contents($path);
} else {
header('HTTP/1.0 404 Not Found');
$content = file_get_contents('view/404.php');
}
?>

Реализуйте в вашем движке отдачу страницы
с 404 ошибкой.

Introduction: Custom 404 Error Page in PHP

Every website gets the occasional, frustrating Error 404: Not Found. And if you have your own website, you may wish to customize these error pages. Thankfully, it’s not that hard to do. Your error pages may be of any extension you want. Usually, they are written in SHTML. But SHTML isn’t very dynamic in terms of what can be done with it. So I went over to PHP for my error pages. The coding wasn’t hard either. So let’s begin.

Step 1: Requirements

If you have a website, your hosing server should have PHP installed. If not, ask your server’s admin if they would be kind enough to install it. If you are just screwing around wasting time, you need some type of emulator. If you’re on Windows, use easyPHP for this. If you’re on Linux and can spare the resources, get: apache2 and php (for Ubuntu, sudo apt-get install apache2 php). If you’re on mac, I have no idea what you can use.

Once you meet these requirements, go to the next step.

Step 2: .htaccess

As stated on the cover page, your custom error page(s) can have any extension you want. But you can’t use it if your server isn’t told to use it. This is where .htaccess comes in. .htaccess is a file named, well, «.htaccess». This file can be used to configure your site to certain degrees. What we will do is go ahead and point the 404 error to 404.php (which, ironically, doesn’t exist yet). This will be a hidden file (every file that begins with a dot is a hidden file). So make sure you can view hidden files. In this file, write the following code and save it:

ErrorDocument 404 /404.php

And while you’re at it, if you feel like it:

ErrorDocument 400 /400.php
ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php #Don't re-add this line
ErrorDocument 500 /500.php

Step 3: 404.php

And the actual error page. I’m going to ignore the whole «let’s follow standards» thing I usually do. The reason I chose PHP for the error page is because you can figure out the source of the error to an extent; you can see if the missing page was typed in the address bar, if it was a link on your site, or if it was a link on a different site. This is achieved by parsing a server variable. You can also parse a couple other server variables and see exactly what was put into the address bar. For this ible, we will only grab the requested page and the referrer, if any.

<?php echo $_SERVER['REQUEST_URI']; ?> does not exist, sorry.

The line above will tell the visitor that the page they want, along with the page’s path (preceded with a slash), does not exist. It’s helpful to tell the specific page because the hyperlink they followed, if they followed, may not reflect the page’s path. The next code will grab if there was a referrer and who it was.

<?php
if(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$refuri = parse_url($_SERVER['HTTP_REFERER']); // use the parse_url() function to create an array containing information about the domain if($refuri['host'] == "your-domain.com"){
//the link was on your site
}
else{ //the link was on another site. $refuri['host'] will return what that site is
} } else{
//the visitor typed gibberish into the address bar
}
?>

On my site, I told the user one of three things to do as per the code. If the referrer was my site, email me and let me know. If the referrer was on a different site, email them and let them know. If they types randomly in the address bar, stop doing that.

<?php
if(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$refuri = parse_url($_SERVER['HTTP_REFERER']); // use the parse_url() function to create an array containing information about the domain
if($refuri['host'] == "cutlery-in-the-toaster.com"){
echo "You should email fork@cutlery-in-the-toaster.com and tell me I have a dead link on this site.";
}
else{
echo "You should email someone over at " . $refuri['host'] . " and let them know they have a dead link to this site.";
}
}
else{
echo "If you got here from Angola, you took a wrong turn at Catumbela. And if you got here by typing randomly in the address bar, stop doing that. You're filling my error logs with unnecessary junk.";
}
?>

Step 4: Testing

First, go to your site like normal. It should show up normally. To test if your .htaccess is being read, insert random junk anywhere inside it and save it. Reloading the page should give a 500 error. If not, make sure your site is set up to use .htaccess files (I just had to edit my server’s config files to get it to work). If it still don’t work, try deleting all the blank spaces and reinserting them.
Else, undo the junk and re-save it. Now try to visit a non-existent page. You should see your 404 page. Add a few dead links on your site and try to follow them. You should end up with the same 404 page but with different content. Add a dead link to another website and the 404 page will have different content.

Step 5: Files

Here are the files used in this ible. Edit as desired/required.

1 Person Made This Project!

Recommendations

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Как вызвать 400 ошибку
  • Как вывести ошибки php на экран