HTTP: headers and status codes

Содержание
Send headers
Status codes that matter
Redirect correctly
Read the user agent

Send headers

The header function sends one raw HTTP header. Call it before any output, including spaces and error messages, or PHP reports headers already sent.

Use headers to declare content type, caching rules, and download names.

header("Content-Type: application/json"); echo json_encode(["ok" => true]);

Status codes that matter

Browsers and APIs decide what happened from the status code, not from the body text. Set it explicitly with http_response_code for errors and empty answers.

Learn five codes first: 200 for success, 201 for created, 400 for bad input, 404 for missing, and 500 for server failure.

http_response_code(404); echo json_encode(["error" => "user not found"]);

Redirect correctly

A redirect is a Location header plus a 3xx status. Send both, then stop the script so no extra output leaks after the redirect.

Use 302 for temporary moves after form posts and 301 only for permanent address changes.

http_response_code(302); header("Location: /ru/code/php/course/39_cookies.php"); exit;

Read the user agent

Browsers send a user agent string that names the client. Read it from the server array when you need device specific output or simple bot detection. See Check your HTTP_USER_AGENT and How to get screen size with PHP.

Never trust it for security decisions, since any client can send any string.

$agent = $_SERVER["HTTP_USER_AGENT"] ?? "unknown"; echo $agent; if (str_contains($agent, "Mobile")) { echo "mobile view"; }

Next: Cookies

Автор статьи: Arthur Isaev

Похожие статьи
Программирование на PHP
PHP course: zero to hero in 50 lessons
What is PHP and where it runs
Install PHP 8.5 and run your first command
Your first PHP script
Comments in PHP
Variables and constants
Types in PHP
Strings in PHP
Numbers in PHP
Operators
if and else
switch and match
Ternary, null coalescing and nullsafe
Loops
Arrays
Associative arrays
Functions
Variable scope
include and require
Namespaces
Composer and autoloading
Everyday string functions
Dates and time
JSON in PHP
Reading and writing files
Errors: read, reproduce, fix
Classes and objects
Constructors and promotion
Inheritance
Interfaces and traits
Enums
Magic methods
Attributes
Exceptions
Strict types
Closures and arrow functions
Generators with yield
Forms: GET and POST
HTTP: headers and status codes
Cookies
Sessions
Login with sessions
JSON REST endpoint
Database with PDO
Uploads and .htaccess
Lint like a pro
Clean functions
Debugging
Modern PHP tour: 5 to 8.4
PHP 8.5 for busy developers
Hero roadmap: the whole course on one page

Поиск по сайту

Канал @aofeed Чат @aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: