← Back to course: PHP from scratch

Exceptions, configuration and best practices

Video coming soon

A professional program does not break at the first problem: the database does not answer, the file does not exist, the user sends something unexpected. What distinguishes a good program is how it reacts. In this lesson you will see how to handle errors with exceptions, how to configure PHP differently in development and in production, how to keep secrets out of the code and a list of best practices that gathers the whole course. It is the last step before the final project.

try, catch, finally and custom exceptions

When something fails, the code throws an exception with throw. If nobody catches it, the program stops. With try you test a block, with catch you capture specific exception types and with finally you run cleanup code no matter what. Catch only what you know how to handle, and from the most specific to the most general; catching Throwable everywhere hides real errors. Creating your own exceptions, which extend Exception, gives clear names to the problem and lets the calling code decide what to do in each case.

php
<?php

declare(strict_types=1);

final class NotFoundException extends RuntimeException
{
}

final class ValidationException extends InvalidArgumentException
{
    /** @param array<string, string> $errors */
    public function __construct(public readonly array $errors)
    {
        parent::__construct('Validation failed');
    }
}

function loadPost(int $id): array
{
    $posts = [1 => ['title' => 'Hello']];
    return $posts[$id] ?? throw new NotFoundException("Post $id not found");
}

function savePost(string $title): void
{
    if (mb_strlen(trim($title)) < 3) {
        throw new ValidationException(['title' => 'Title is too short']);
    }
}

try {
    echo loadPost(1)['title'], "\n";   // Hello
    loadPost(9);
} catch (NotFoundException $e) {
    echo 'Not found: ', $e->getMessage(), "\n"; // Not found: Post 9 not found
} finally {
    echo "Done\n";                     // always runs
}

try {
    savePost('ab');
} catch (ValidationException $e) {
    print_r($e->errors);               // [title] => Title is too short
}

Errors in development and in production

In development you want to see all errors on screen to fix them; in production never. An error message on screen can reveal paths, table names and even pieces of queries, and is gold for an attacker. In production set display_errors=Off and log_errors=On, so details go to a log file, and show the user a generic page with a 500 code. With set_exception_handler you define a global handler for exceptions nobody caught, the ideal place to log and show that page.

php
<?php
// File: src/bootstrap.php
declare(strict_types=1);

$isDev = (getenv('APP_ENV') ?: 'production') === 'development';

error_reporting(E_ALL);
ini_set('display_errors', $isDev ? '1' : '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/../var/php-errors.log');

set_exception_handler(function (Throwable $e) use ($isDev): void {
    error_log($e::class . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    if ($isDev) {
        echo '<pre>', htmlspecialchars((string) $e, ENT_QUOTES, 'UTF-8'), '</pre>';
    } else {
        echo 'Something went wrong. Please try again later.';
    }
});

// Turn warnings and notices into exceptions so they cannot go unnoticed
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
    if (!(error_reporting() & $severity)) {
        return false;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
});

Secrets and best practices

Database passwords, API keys and any secret are not written in the code nor committed to Git. Keep them in environment variables or in a .env file outside the public folder, and add .env to the .gitignore file. Have a .env.example file, with no real values, to document which variables are needed. If you ever commit a secret by mistake, consider it compromised: change it immediately, even if you delete the file later, because the Git history keeps it.

  • Start every file with declare(strict_types=1) and type parameters, returns and properties.
  • Validate all input and escape all output with htmlspecialchars.
  • Always use prepared statements; never concatenate SQL.
  • Store passwords with password_hash and verify with password_verify.
  • Protect actions that change data with POST and a CSRF token.
  • Follow the PSR-12 standard and use PHPStan or Psalm to catch errors before running.
  • Write PHPUnit tests for the important logic.
  • Keep PHP and dependencies updated with composer update and watch security advisories.

Test what you learned

Question 1 of 1

Which setting is correct in production?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →