Log in Sign up

Superglobals

Available everywhere, in every scope:

VariableContains
$_GETURL query parameters (?id=5)
$_POSTform data sent by POST
$_REQUESTGET + POST + COOKIE mixed – avoid
$_FILESuploaded files (see PHP Files and Directories)
$_COOKIEcookies from the browser
$_SESSIONsession data (after session_start())
$_SERVERrequest and server info
$_ENV / getenv('NAME')environment variables

Useful $_SERVER keys: REQUEST_METHOD, REQUEST_URI, HTTP_HOST, REMOTE_ADDR, HTTP_USER_AGENT, HTTPS, SCRIPT_NAME.

Handling a form

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $age   = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);

    $errors = [];
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email';
    if ($age === false || $age === null)            $errors[] = 'Invalid age';
}
?>
<input name="email" value="<?= htmlspecialchars($email ?? '', ENT_QUOTES, 'UTF-8') ?>">

<?= $x ?> is short for <?php echo $x; ?>.

FilterChecks
FILTER_VALIDATE_INTinteger (options: min_range, max_range)
FILTER_VALIDATE_FLOATfloat
FILTER_VALIDATE_EMAILemail address
FILTER_VALIDATE_URLURL
FILTER_VALIDATE_IPIP address
FILTER_VALIDATE_BOOLEAN"1", "true", "on", "yes" → true

Headers and redirects

header('Location: /thanks.php');           // redirect
exit;                                      // always stop after a redirect

header('Content-Type: application/json; charset=utf-8');
http_response_code(404);

Headers must be sent before any output (even a space or BOM). headers_sent() tells you if it is too late.

Sessions

session_start();                           // before any output, on every page

$_SESSION['user_id'] = 42;                 // store
$id = $_SESSION['user_id'] ?? null;        // read
unset($_SESSION['cart']);                  // remove one value

session_regenerate_id(true);               // after login: prevents session fixation

// logout
$_SESSION = [];
session_destroy();

Cookies

setcookie('theme', 'dark', [
    'expires'  => time() + 60 * 60 * 24 * 30,   // 30 days
    'path'     => '/',
    'secure'   => true,       // HTTPS only
    'httponly' => true,       // not readable by JavaScript
    'samesite' => 'Lax',
]);

$theme = $_COOKIE['theme'] ?? 'light';          // available on the next request

setcookie('theme', '', time() - 3600, '/');     // delete

Passwords

$hash = password_hash($password, PASSWORD_DEFAULT);   // store this (bcrypt/argon)

if (password_verify($input, $hash)) {
    if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
        // update stored hash
    }
}

Never use md5 or sha1 for passwords.

Security checklist

ThreatProtection
XSS (injected scripts)htmlspecialchars($s, ENT_QUOTES, 'UTF-8') on every output
SQL injectionprepared statements – see PHP Databases with PDO
CSRFtoken in session + hidden form field, compare with hash_equals()
Session theftHTTPS, httponly/secure cookies, session_regenerate_id(true)
Weak tokensbin2hex(random_bytes(32))
Path traversalbasename() on user file names, check realpath() stays in your folder

CSRF token:

// create once per session
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));

// check when the form is posted
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
    http_response_code(403);
    exit;
}
<input type="hidden" name="csrf" value="<?= $_SESSION['csrf'] ?>">

Previous: PHP Files and Directories · Next: PHP Databases with PDO

Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.