Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

HTTP requests and responses

The browser and the server talk over the HTTP protocol: the browser sends a request, the server returns a response. PHP runs for every request, receives its data and builds the response. Understanding this lets you not only print pages but also redirect, serve files and build APIs.

The examples in this lesson need a web server, so they cannot be run here.

What a request consists of

A request has a method (GET, POST), an address, headers and sometimes a body. PHP puts all of this into the $_SERVER array:

<?php
 
echo $_SERVER['REQUEST_METHOD']; // GET
echo $_SERVER['REQUEST_URI'];    // /products?page=2

GET is used for reading pages, POST for sending data that changes something.

Handling methods differently

The same address can show a form and accept it:

<?php
 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo 'The form was submitted';
} else {
    echo 'Showing the form';
}

The status code

A response starts with a code: 200 means everything is fine, 404 not found, 500 a server error. The http_response_code() function sets it:

<?php
 
$product = null;
 
if ($product === null) {
    http_response_code(404);
    echo 'Product not found';
}

Without this line the "not found" page would go out with code 200, and a search engine would take it for a regular one.

Response headers

Headers tell the browser what it has received. The header() function sends them:

<?php
 
header('Content-Type: text/plain; charset=utf-8');
 
echo 'Plain text, not HTML';

Redirecting

The Location header sends the browser to another address. The program is ended right after it:

<?php
 
header('Location: /login');
exit;

A redirect after a form is handled successfully is a must: otherwise refreshing the page submits the form again.

A JSON response

An API returns data rather than pages. For that, set the type application/json and print the result of json_encode():

<?php
 
header('Content-Type: application/json; charset=utf-8');
 
echo json_encode(['id' => 1, 'title' => 'Tea']);

A JSON request body

Data sent as JSON does not end up in $_POST. It is read from the php://input stream:

<?php
 
$body = file_get_contents('php://input');
$data = json_decode($body, true) ?? [];
 
echo $data['title'] ?? 'No title was sent';

Common mistake

Headers are sent before the page content. If something has already been printed before the header() call — even a space or an empty line before <?php — PHP raises the warning Cannot modify header information, and the redirect does not work. Call header() before any output.

Thanks for reading!

Donate to the site — we work hard for you.