PHP Cheatsheet

Web and Security

Use this PHP reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Superglobals

$_GET['q'] ?? '';
$_POST['email'] ?? '';
$_COOKIE['session'] ?? null;
$_SERVER['REQUEST_METHOD'];

Browser input is untrusted. Validate before using it and escape for the output context.

HTML Escaping

echo htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

Use this for text inserted into HTML. Escaping is context-specific; HTML escaping is not SQL escaping.

Input Validation

$email = filter_var($raw, FILTER_VALIDATE_EMAIL);
$id = filter_var($rawId, FILTER_VALIDATE_INT);

Check required fields, lengths, allowed values, and numeric ranges.

Sessions

session_start();
$_SESSION['user_id'] = $userId;

Call session_start() before output. Regenerate session IDs after login with session_regenerate_id(true).

Cookies

setcookie('theme', 'dark', [
    'expires' => time() + 60 * 60 * 24 * 30,
    'path' => '/',
    'secure' => true,      // HTTPS only
    'httponly' => true,    // hidden from JavaScript
    'samesite' => 'Lax',   // Lax, Strict, or None
]);

Always set secure, httponly, and samesite on anything session-like. SameSite=None requires secure and reopens cross-site sending, so use it only for legitimate cross-site needs. Apply the same options to the session cookie via session_set_cookie_params() before session_start().

CSRF Tokens

// on render
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$field = '<input type="hidden" name="csrf" value="' . $_SESSION['csrf'] . '">';

// on submit
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
    http_response_code(403);
    exit;
}

Generate tokens with random_bytes and compare with hash_equals (constant-time, prevents timing attacks). SameSite cookies reduce CSRF risk but a token is still the standard defense for state-changing form posts.

Passwords

$hash = password_hash($password, PASSWORD_DEFAULT);
$ok = password_verify($password, $hash);

if ($ok && password_needs_rehash($hash, PASSWORD_DEFAULT)) {
    $newHash = password_hash($password, PASSWORD_DEFAULT);
    // persist $newHash for this user
}

Never store plaintext passwords. Let PHP choose the current default hashing algorithm, and rehash at login when password_needs_rehash reports the stored hash uses outdated settings.

Headers and JSON Responses

header('Content-Type: application/json');
http_response_code(201);
echo json_encode(['ok' => true], JSON_THROW_ON_ERROR);

Send headers before body output.