Log in Sign up

Error reporting

// development
error_reporting(E_ALL);
ini_set('display_errors', '1');

// production: log, don't show
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/../logs/php-error.log');
LevelMeaning
E_ERRORfatal error, script stops
E_WARNINGproblem, script continues
E_NOTICEminor issue
E_DEPRECATEDfeature will be removed
E_ALLeverything

Exceptions

function divide(int $a, int $b): float {
    if ($b === 0) {
        throw new InvalidArgumentException('Division by zero');
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (InvalidArgumentException $e) {
    echo 'Input error: ' . $e->getMessage();
} catch (Throwable $e) {                    // catches everything (Exception + Error)
    error_log($e);
} finally {
    // always runs (close files, connections …)
}
MethodReturns
$e->getMessage()error text
$e->getCode()error code
$e->getFile() / $e->getLine()where it was thrown
$e->getTraceAsString()call stack
$e->getPrevious()wrapped exception

Common built-in classes: Exception, RuntimeException, InvalidArgumentException, LogicException, TypeError, ValueError, JsonException, PDOException.

class PaymentException extends RuntimeException {}   // own exception type

set_exception_handler(function (Throwable $e) {       // last line of defence
    error_log($e);
    http_response_code(500);
    echo 'Something went wrong.';
});

Logging and debugging

ToolUse
var_dump($x)type and value
print_r($x, true)readable string of arrays/objects
error_log("msg")write to the error log
debug_print_backtrace()show how you got here
memory_get_usage() / memory_get_peak_usage()memory in bytes
microtime(true)measure run time
Xdebug extensionstep debugging in the IDE
$start = microtime(true);
// … code …
printf("%.3f s\n", microtime(true) - $start);

JSON

$data = ['name' => 'Anna', 'tags' => ['php', 'äöü']];

$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);

$arr  = json_decode($json, true, 512, JSON_THROW_ON_ERROR);  // true = associative array
$obj  = json_decode($json);                                   // stdClass object: $obj->name

json_validate($json);   // PHP 8.3: check without decoding

Without JSON_THROW_ON_ERROR, check json_last_error() !== JSON_ERROR_NONE and json_last_error_msg().

Simple JSON API response:

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => true, 'items' => $items], JSON_THROW_ON_ERROR);
exit;

PHP on the command line

CommandDoes
php -vversion
php -mloaded extensions
php -ifull configuration (like phpinfo())
php --iniwhich php.ini files are used
php -l file.phpsyntax check (lint)
php script.php arg1run a script; args in $argv, count in $argc
php -r 'echo 1+1;'run code directly
php -ainteractive shell
php -S localhost:8000 -t publicbuilt-in dev web server (not for production)

Composer (package manager)

CommandDoes
composer initcreate composer.json
composer require vendor/packageadd a package
composer require --dev phpunit/phpunitadd a dev-only package
composer installinstall from composer.lock
composer updateupdate packages within version limits
composer dump-autoloadrebuild the autoloader

Load everything with require __DIR__ . '/vendor/autoload.php';

For server-side commands (services, logs, Docker) see Linux & Docker Command Cheat Sheet.

Previous: PHP Databases with PDO · Start: PHP Basics: Syntax, Variables and Output

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.