PHP 8 cheatsheet

PHP 8: Web, security and database

10 common PHP 8 tasks.

Connect with PDO

Connect to MySQL with exceptions on errors. Use real credentials from the environment.

$pdo = new PDO(
    'mysql:host=127.0.0.1;dbname=app;charset=utf8mb4',
    getenv('DB_USER'),
    getenv('DB_PASSWORD'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);

Run a prepared statement

Pass values separately from the SQL, which prevents SQL injection.

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

Caution: Never build SQL by joining user input into the string.

Hash a password

Hash passwords with a strong algorithm and a built-in salt. Never store plain text.

$hash = password_hash($password, PASSWORD_DEFAULT);

Check a password

Compare a password with a stored hash.

if (password_verify($password, $hash)) {
    // log the user in
}

Escape output

Escape user-provided values before printing them in HTML, to prevent cross-site scripting.

echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

Validate input

Check that a value is a valid email address.

$ok = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;

Start a session

Call it before any output.

session_start();
$_SESSION['user_id'] = $user['id'];

Redirect

Send a redirect and stop the script.

header('Location: /login', true, 302);
exit;

Handle exceptions

Catch specific exceptions and always run cleanup in finally.

try {
    $result = riskyOperation();
} catch (InvalidArgumentException $e) {
    error_log($e->getMessage());
} finally {
    cleanup();
}

Use namespaces and autoloading

Declare a namespace, then load classes through Composer's autoloader.

namespace App\Services;

use App\Models\User;

require __DIR__ . '/vendor/autoload.php';

Was this page helpful?