- doctor Brain
- Статус 404
- Статус 400
- Статус 301
- Особенности кода
- Новые публикации
- JavaScript: сохраняем страницу в pdf
- HTML: Полезные примеры
- CSS: Ускоряем загрузку страницы
- JavaScript: 5 странностей
- JavaScript: конструктор сортировщиков
- Категории
- О нас
- ewwink / http_response_code.php
- henriquemoody / http-status-codes.php
doctor Brain
Для того, чтобы установить определенный код ответа HTTP, в PHP есть встроенная функция http_response_code() .
К счастью для нас, в PHP есть множество встроенных функций, обеспечивающих взаимодействие с веб-интерфейсом. Функция http_response_code() — одна из них, с ее помощью мы можем установить желаемый статус ответа, в том числе: 400, 404, 301, 200, используя всего одну строку кода.
Итак, обратимся к примерам:
Статус 404
http_response_code(404); exit;
Устанавливает статус ответа 404 Not Found — “не найден” (сервер не может найти запрашиваемый ресурс).
Статус 400
http_response_code(400); exit;
Устанавливает статус ответа 400 Bad Request — “плохой запрос” (сервер не понимает запрос из-за неверного синтаксиса).
Статус 301
http_response_code(301); exit;
Устанавливает статус ответа 301 Moved Permanently — “перемещен на постоянной основе” (URI запроса был изменен, новый URI может быть предоставлен в ответе).
Особенности кода
- Вызываем функцию http_response_code , передавая в качестве аргумента желаемый статус, как целое число.
- Принудительно завершаем скрипт до появления нежелательного поведения, способного привести к смене ответа на “200 ОК”.
Новые публикации
JavaScript: сохраняем страницу в pdf
HTML: Полезные примеры
CSS: Ускоряем загрузку страницы
JavaScript: 5 странностей
JavaScript: конструктор сортировщиков
Категории
О нас
Frontend & Backend. Статьи, обзоры, заметки, код, уроки.
© 2021 dr.Brain .
мир глазами веб-разработчика
ewwink / http_response_code.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* StatusCodes provides named constants for |
* HTTP protocol status codes. Written for the |
* Recess Framework (http://www.recessframework.com/) |
* |
* @author Kris Jordan |
* @license MIT |
* @package recess.http |
* |
* usage: |
*/ |
class StatusCodes |
// [Informational 1xx] |
const HTTP_CONTINUE = 100 ; |
const HTTP_SWITCHING_PROTOCOLS = 101 ; |
// [Successful 2xx] |
const HTTP_OK = 200 ; |
const HTTP_CREATED = 201 ; |
const HTTP_ACCEPTED = 202 ; |
const HTTP_NONAUTHORITATIVE_INFORMATION = 203 ; |
const HTTP_NO_CONTENT = 204 ; |
const HTTP_RESET_CONTENT = 205 ; |
const HTTP_PARTIAL_CONTENT = 206 ; |
// [Redirection 3xx] |
const HTTP_MULTIPLE_CHOICES = 300 ; |
const HTTP_MOVED_PERMANENTLY = 301 ; |
const HTTP_FOUND = 302 ; |
const HTTP_SEE_OTHER = 303 ; |
const HTTP_NOT_MODIFIED = 304 ; |
const HTTP_USE_PROXY = 305 ; |
const HTTP_UNUSED = 306 ; |
const HTTP_TEMPORARY_REDIRECT = 307 ; |
// [Client Error 4xx] |
const errorCodesBeginAt = 400 ; |
const HTTP_BAD_REQUEST = 400 ; |
const HTTP_UNAUTHORIZED = 401 ; |
const HTTP_PAYMENT_REQUIRED = 402 ; |
const HTTP_FORBIDDEN = 403 ; |
const HTTP_NOT_FOUND = 404 ; |
const HTTP_METHOD_NOT_ALLOWED = 405 ; |
const HTTP_NOT_ACCEPTABLE = 406 ; |
const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407 ; |
const HTTP_REQUEST_TIMEOUT = 408 ; |
const HTTP_CONFLICT = 409 ; |
const HTTP_GONE = 410 ; |
const HTTP_LENGTH_REQUIRED = 411 ; |
const HTTP_PRECONDITION_FAILED = 412 ; |
const HTTP_REQUEST_ENTITY_TOO_LARGE = 413 ; |
const HTTP_REQUEST_URI_TOO_LONG = 414 ; |
const HTTP_UNSUPPORTED_MEDIA_TYPE = 415 ; |
const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416 ; |
const HTTP_EXPECTATION_FAILED = 417 ; |
// [Server Error 5xx] |
const HTTP_INTERNAL_SERVER_ERROR = 500 ; |
const HTTP_NOT_IMPLEMENTED = 501 ; |
const HTTP_BAD_GATEWAY = 502 ; |
const HTTP_SERVICE_UNAVAILABLE = 503 ; |
const HTTP_GATEWAY_TIMEOUT = 504 ; |
const HTTP_VERSION_NOT_SUPPORTED = 505 ; |
private static $ messages = array ( |
// [Informational 1xx] |
100 => ‘100 Continue’ , 101 => ‘101 Switching Protocols’ , |
// [Successful 2xx] |
200 => ‘200 OK’ , 201 => ‘201 Created’ , 202 => ‘202 Accepted’ , 203 => ‘203 Non-Authoritative Information’ , 204 => ‘204 No Content’ , 205 => ‘205 Reset Content’ , 206 => ‘206 Partial Content’ , |
// [Redirection 3xx] |
300 => ‘300 Multiple Choices’ , 301 => ‘301 Moved Permanently’ , 302 => ‘302 Found’ , 303 => ‘303 See Other’ , 304 => ‘304 Not Modified’ , 305 => ‘305 Use Proxy’ , 306 => ‘306 (Unused)’ , 307 => ‘307 Temporary Redirect’ , |
// [Client Error 4xx] |
400 => ‘400 Bad Request’ , 401 => ‘401 Unauthorized’ , 402 => ‘402 Payment Required’ , 403 => ‘403 Forbidden’ , 404 => ‘404 Not Found’ , 405 => ‘405 Method Not Allowed’ , 406 => ‘406 Not Acceptable’ , 407 => ‘407 Proxy Authentication Required’ , 408 => ‘408 Request Timeout’ , 409 => ‘409 Conflict’ , 410 => ‘410 Gone’ , 411 => ‘411 Length Required’ , 412 => ‘412 Precondition Failed’ , 413 => ‘413 Request Entity Too Large’ , 414 => ‘414 Request-URI Too Long’ , 415 => ‘415 Unsupported Media Type’ , 416 => ‘416 Requested Range Not Satisfiable’ , 417 => ‘417 Expectation Failed’ , |
// [Server Error 5xx] |
500 => ‘500 Internal Server Error’ , 501 => ‘501 Not Implemented’ , 502 => ‘502 Bad Gateway’ , 503 => ‘503 Service Unavailable’ , 504 => ‘504 Gateway Timeout’ , 505 => ‘505 HTTP Version Not Supported’ ); |
public static function httpHeaderFor ( $ code ) |
return ‘HTTP/1.1 ‘ . self :: $ messages [ $ code ]; |
> |
public static function getMessageForCode ( $ code ) |
return self :: $ messages [ $ code ]; |
> |
public static function isError ( $ code ) |
return is_numeric( $ code ) && $ code >= self :: HTTP_BAD_REQUEST ; |
> |
public static function canHaveBody ( $ code ) |
return |
// True if not in 100s |
( $ code < self :: HTTP_CONTINUE || $ code >= self :: HTTP_OK ) && // and not 204 NO CONTENT |
$ code != self :: HTTP_NO_CONTENT && // and not 304 NOT MODIFIED |
$ code != self :: HTTP_NOT_MODIFIED ; |
> |
> |
?> |
henriquemoody / http-status-codes.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Content from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes |
* |
* You may also want a list of unofficial codes: |
* |
* 103 => ‘Checkpoint’, |
* 218 => ‘This is fine’, // Apache Web Server |
* 419 => ‘Page Expired’, // Laravel Framework |
* 420 => ‘Method Failure’, // Spring Framework |
* 420 => ‘Enhance Your Calm’, // Twitter |
* 430 => ‘Request Header Fields Too Large’, // Shopify |
* 450 => ‘Blocked by Windows Parental Controls’, // Microsoft |
* 498 => ‘Invalid Token’, // Esri |
* 499 => ‘Token Required’, // Esri |
* 509 => ‘Bandwidth Limit Exceeded’, // Apache Web Server/cPanel |
* 526 => ‘Invalid SSL Certificate’, // Cloudflare and Cloud Foundry’s gorouter |
* 529 => ‘Site is overloaded’, // Qualys in the SSLLabs |
* 530 => ‘Site is frozen’, // Pantheon web platform |
* 598 => ‘Network read timeout error’, // Informal convention |
* 440 => ‘Login Time-out’, // IIS |
* 449 => ‘Retry With’, // IIS |
* 451 => ‘Redirect’, // IIS |
* 444 => ‘No Response’, // nginx |
* 494 => ‘Request header too large’, // nginx |
* 495 => ‘SSL Certificate Error’, // nginx |
* 496 => ‘SSL Certificate Required’, // nginx |
* 497 => ‘HTTP Request Sent to HTTPS Port’, // nginx |
* 499 => ‘Client Closed Request’, // nginx |
* 520 => ‘Web Server Returned an Unknown Error’, // Cloudflare |
* 521 => ‘Web Server Is Down’, // Cloudflare |
* 522 => ‘Connection Timed Out’, // Cloudflare |
* 523 => ‘Origin Is Unreachable’, // Cloudflare |
* 524 => ‘A Timeout Occurred’, // Cloudflare |
* 525 => ‘SSL Handshake Failed’, // Cloudflare |
* 526 => ‘Invalid SSL Certificate’, // Cloudflare |
* 527 => ‘Railgun Error’, // Cloudflare |
*/ |
return [ |
100 => ‘Continue’ , |
101 => ‘Switching Protocols’ , |
102 => ‘Processing’ , // WebDAV; RFC 2518 |
103 => ‘Early Hints’ , // RFC 8297 |
200 => ‘OK’ , |
201 => ‘Created’ , |
202 => ‘Accepted’ , |
203 => ‘Non-Authoritative Information’ , // since HTTP/1.1 |
204 => ‘No Content’ , |
205 => ‘Reset Content’ , |
206 => ‘Partial Content’ , // RFC 7233 |
207 => ‘Multi-Status’ , // WebDAV; RFC 4918 |
208 => ‘Already Reported’ , // WebDAV; RFC 5842 |
226 => ‘IM Used’ , // RFC 3229 |
300 => ‘Multiple Choices’ , |
301 => ‘Moved Permanently’ , |
302 => ‘Found’ , // Previously «Moved temporarily» |
303 => ‘See Other’ , // since HTTP/1.1 |
304 => ‘Not Modified’ , // RFC 7232 |
305 => ‘Use Proxy’ , // since HTTP/1.1 |
306 => ‘Switch Proxy’ , |
307 => ‘Temporary Redirect’ , // since HTTP/1.1 |
308 => ‘Permanent Redirect’ , // RFC 7538 |
400 => ‘Bad Request’ , |
401 => ‘Unauthorized’ , // RFC 7235 |
402 => ‘Payment Required’ , |
403 => ‘Forbidden’ , |
404 => ‘Not Found’ , |
405 => ‘Method Not Allowed’ , |
406 => ‘Not Acceptable’ , |
407 => ‘Proxy Authentication Required’ , // RFC 7235 |
408 => ‘Request Timeout’ , |
409 => ‘Conflict’ , |
410 => ‘Gone’ , |
411 => ‘Length Required’ , |
412 => ‘Precondition Failed’ , // RFC 7232 |
413 => ‘Payload Too Large’ , // RFC 7231 |
414 => ‘URI Too Long’ , // RFC 7231 |
415 => ‘Unsupported Media Type’ , // RFC 7231 |
416 => ‘Range Not Satisfiable’ , // RFC 7233 |
417 => ‘Expectation Failed’ , |
418 => ‘I\’m a teapot’ , // RFC 2324, RFC 7168 |
421 => ‘Misdirected Request’ , // RFC 7540 |
422 => ‘Unprocessable Entity’ , // WebDAV; RFC 4918 |
423 => ‘Locked’ , // WebDAV; RFC 4918 |
424 => ‘Failed Dependency’ , // WebDAV; RFC 4918 |
425 => ‘Too Early’ , // RFC 8470 |
426 => ‘Upgrade Required’ , |
428 => ‘Precondition Required’ , // RFC 6585 |
429 => ‘Too Many Requests’ , // RFC 6585 |
431 => ‘Request Header Fields Too Large’ , // RFC 6585 |
451 => ‘Unavailable For Legal Reasons’ , // RFC 7725 |
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’ , // RFC 2295 |
507 => ‘Insufficient Storage’ , // WebDAV; RFC 4918 |
508 => ‘Loop Detected’ , // WebDAV; RFC 5842 |
510 => ‘Not Extended’ , // RFC 2774 |
511 => ‘Network Authentication Required’ , // RFC 6585 |
]; |