Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PHP
PHP
0/12 completed
Beginner
Hello PHPVariables and arraysControl flowFunctions
Intermediate
Strings, dates and JSONForms, requests and sessionsDatabases with PDO
Advanced
Object-oriented PHPErrors, exceptions and typesSecurity essentials
Pro
Composer, autoloading and testingLaravel basics
Tracks / PHP / Intermediate

Forms, requests and sessions

PHP was built to answer web requests. For every request, the web server runs your script with the request's details already filled in: query parameters, form fields, cookies and headers. Your script reads them, decides what to do, and prints the response. This lesson builds a small login form to show how it all fits together.

💡 Requests need a web server, which the in-browser editor doesn't have. The examples below use PHP's built-in server (php -S) and curl (a command-line HTTP client). Every output shown was produced by actually running them with PHP 8.5.

The request superglobals

PHP fills these arrays before your script runs:

Variable Contains
$_GET Query-string parameters: /search?q=php → $_GET['q']
$_POST Fields of a submitted form (method="post")
$_COOKIE Cookies sent by the browser
$_FILES Uploaded files
$_SERVER Request details: method, path, headers, client IP
$_SESSION Your per-visitor session data (after session_start())

Here's a script that shows a few of them:

site/info.php
<?php
header('Content-Type: text/plain');
echo "method: ", $_SERVER['REQUEST_METHOD'], "\n";
echo "path:   ", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), "\n";
echo "q:      ", $_GET['q'] ?? '(none)', "\n";
echo "page:   ", (int) ($_GET['page'] ?? 1), "\n";
echo "agent:  ", $_SERVER['HTTP_USER_AGENT'] ?? '-', "\n";
bash
cd site
php -S 127.0.0.1:8000 &        # start the server in the background
curl -s "http://127.0.0.1:8000/info.php?q=php+forms&page=2" -A "my-browser"
Output
method: GET
path:   /info.php
q:      php forms
page:   2
agent:  my-browser

php -S 127.0.0.1:8000 serves the current folder: a request for /info.php runs info.php. It's perfect for development (never for production, where nginx or Apache with PHP-FPM does the job).

Notice (int) ($_GET['page'] ?? 1): everything from the request is a string (or missing), so convert and validate it before use.

Handling a form

A typical page shows a form on GET and processes it on POST. This one validates input with filter_var:

site/signup.php
<?php
$errors = [];
$email = '';
$age = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $age = trim($_POST['age'] ?? '');

    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $errors[] = 'Please enter a valid email address.';
    }
    $ageNumber = filter_var($age, FILTER_VALIDATE_INT, ['options' => ['min_range' => 13, 'max_range' => 120]]);
    if ($ageNumber === false) {
        $errors[] = 'Age must be a whole number between 13 and 120.';
    }

    if (!$errors) {
        // save the user… then redirect, so refreshing doesn't resubmit the form
        header('Location: /welcome.php?email=' . urlencode($email), true, 303);
        exit;
    }
    http_response_code(422);
}
$e = fn(string $s): string => htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
?>
<form method="post" action="/signup.php">
<?php foreach ($errors as $error): ?>
  <p class="error"><?= $e($error) ?></p>
<?php endforeach; ?>
  <input name="email" value="<?= $e($email) ?>">
  <input name="age" value="<?= $e($age) ?>">
  <button>Sign up</button>
</form>

Let's submit it twice: once with bad input, once with good input:

bash
cd site
echo "--- invalid:"
curl -s -w "status %{http_code}\n" -d "email=not-an-email&age=9" http://127.0.0.1:8000/signup.php | grep -E "error|status|value="
echo "--- valid:"
curl -s -o /dev/null -w "status %{http_code}, redirect to %{redirect_url}\n" -d "email=asha@example.com&age=31" http://127.0.0.1:8000/signup.php
Output
--- invalid:
  <p class="error">Please enter a valid email address.</p>
  <p class="error">Age must be a whole number between 13 and 120.</p>
  <input name="email" value="not-an-email">
  <input name="age" value="9">
status 422
--- valid:
status 303, redirect to http://127.0.0.1:8000/welcome.php?email=asha%40example.com

Three habits shown here:

  1. Validate everything from the request on the server, even if the browser form already checks it: anyone can send any request with curl.
  2. Escape output with htmlspecialchars when you put user data back into HTML, so a "name" like <script>… is shown as text instead of running. (More in Security essentials.)
  3. Post/Redirect/Get: after a successful POST, redirect (status 303) so refreshing the page doesn't submit the form again.
filter_var filter Checks
FILTER_VALIDATE_EMAIL An email address
FILTER_VALIDATE_INT (with min_range/max_range) An integer, optionally in a range
FILTER_VALIDATE_FLOAT A decimal number
FILTER_VALIDATE_URL A URL
FILTER_VALIDATE_BOOL "1", "true", "on", "yes" → true

Cookies and sessions

HTTP is stateless: each request arrives on its own. To remember a visitor ("logged in as Asha", "3 items in cart") PHP uses a session: data kept on the server, linked to the browser by a cookie holding a random session ID.

site/login.php
<?php
session_start([
    'cookie_httponly' => true,     // JavaScript can't read the session cookie
    'cookie_samesite' => 'Lax',    // not sent on most cross-site requests
]);

$users = ['asha' => password_hash('s3cret!', PASSWORD_DEFAULT)];   // normally from a database

$action = $_GET['action'] ?? 'status';
if ($action === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = $_POST['user'] ?? '';
    $hash = $users[$user] ?? null;
    if ($hash && password_verify($_POST['password'] ?? '', $hash)) {
        session_regenerate_id(true);    // new ID after login (prevents session fixation)
        $_SESSION['user'] = $user;
        $_SESSION['visits'] = 0;
        echo "Welcome, $user!\n";
    } else {
        http_response_code(401);
        echo "Wrong user name or password.\n";
    }
} elseif ($action === 'logout') {
    $_SESSION = [];
    session_destroy();
    echo "Logged out.\n";
} elseif (isset($_SESSION['user'])) {
    $_SESSION['visits']++;
    echo "Logged in as {$_SESSION['user']}, visit {$_SESSION['visits']}.\n";
} else {
    echo "Not logged in.\n";
}

curl -c jar -b jar stores and sends cookies like a browser would:

bash
cd site
J="-s -c jar.txt -b jar.txt"
curl $J http://127.0.0.1:8000/login.php
curl $J -w "(status %{http_code})\n" -d "user=asha&password=wrong" "http://127.0.0.1:8000/login.php?action=login"
curl $J -d "user=asha&password=s3cret!" "http://127.0.0.1:8000/login.php?action=login"
curl $J http://127.0.0.1:8000/login.php
curl $J http://127.0.0.1:8000/login.php
grep -c PHPSESSID jar.txt
curl $J "http://127.0.0.1:8000/login.php?action=logout"
curl $J http://127.0.0.1:8000/login.php
Output
Not logged in.
Wrong user name or password.
(status 401)
Welcome, asha!
Logged in as asha, visit 1.
Logged in as asha, visit 2.
1
Logged out.
Not logged in.
  • session_start() must run before any output. It reads the session cookie (PHPSESSID) and loads $_SESSION.
  • Store passwords only as hashes from password_hash, and check them with password_verify.
  • Regenerate the session ID after logging in, and destroy the session on logout.

To set your own cookie: setcookie('theme', 'dark', ['expires' => time() + 86400 * 30, 'httponly' => true, 'samesite' => 'Lax']). Cookies live in the browser and can be changed by the user, so never trust them for anything important: that's what sessions are for.

JSON APIs

Many PHP apps are APIs for JavaScript or mobile front ends. Read a JSON body from php://input and reply with JSON:

site/api.php
<?php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'use POST']);
    exit;
}
try {
    $data = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid JSON']);
    exit;
}
$items = $data['items'] ?? [];
$total = array_sum(array_map(fn($i) => $i['qty'] * $i['price'], $items));
echo json_encode(['items' => count($items), 'total' => round($total, 2)]);
bash
cd site
curl -s -X POST -H "Content-Type: application/json" -d '{"items":[{"qty":2,"price":19.99},{"qty":1,"price":49.5}]}' http://127.0.0.1:8000/api.php; echo
curl -s -w " (%{http_code})\n" -X POST -d '{broken' http://127.0.0.1:8000/api.php
curl -s -w " (%{http_code})\n" http://127.0.0.1:8000/api.php
Output
{"items":2,"total":89.48}
{"error":"invalid JSON"} (400)
{"error":"use POST"} (405)

Practice

  1. Write hello.php that greets ?name=… from the query string, escaping the name, with "stranger" as the default.
  2. Add a "confirm password" field to the signup form and check that both match.
  3. Use a session to count how many times a visitor has loaded a page.
  4. Write an API endpoint that accepts {"celsius": 21.5} and returns the temperature in Fahrenheit.
✎ Check your understanding

1.Where does PHP put the fields of a submitted POST form?

2.Why redirect after successfully handling a POST form?

3.Where is session data stored?

4.How should passwords be stored?

← Strings, dates and JSON