Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 147 ยท Errors and Exceptions

Debugging PHP

Learn to debug PHP - inspect values with var_dump, print_r and var_export, read stack traces, use debug_backtrace and error logs, set up Xdebug and use assert().

Debugging is the work of finding out why a program does something different from what you expected. It's a skill, not a tool: you form a guess ("the discount is applied twice"), collect evidence (print the value before and after), and narrow the problem down until the cause is obvious. PHP gives you everything you need for that evidence, from a one-line var_dump() to a full step debugger that pauses your code and lets you look around.

This lesson walks through the tools in the order you'll usually reach for them: dumping values, reading error messages and stack traces, asking PHP where you are with debug_backtrace(), writing to the log, stepping through code with Xdebug, and catching wrong assumptions early with assert(). It builds on Errors, Warnings and Notices and Exceptions.

Look at the actual values

Most bugs come down to a value that isn't what you think it is: a string where you expected a number, null instead of an array, a key with a typo. So the first step is nearly always to look. PHP has three built-in ways to print a value for a human, and they show different amounts of detail:

PHP var_dump, print_r and var_export side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Compare the three outputs:

  • print_r() is the most compact and readable, but it hides types: false and null both print as nothing, and '1042' looks the same as the number 1042. Fine for getting an overview of a big array, misleading when the bug is about types.
  • var_dump() shows everything: the type and length of each string (string(4) "1042"), bool(false), NULL, float(19.9), and the size of each array. When in doubt, use var_dump().
  • var_export() prints valid PHP code ('paid' => false, 'coupon' => NULL). You can paste it straight into a test as an expected value, or use var_export($value, true) to get it as a string.

In this example var_dump() immediately reveals that id is a string, which would explain a failing $order['id'] === 1042 check.

print_r($value, true) and var_export($value, true) return the text instead of printing it, which is how you put a dump into a log line: error_log('Order: ' . print_r($order, true));. var_dump() has no such flag; wrap it in output buffering (ob_start() and ob_get_clean()) if you need its output as a string.

Label your dumps

A screen full of anonymous dumps is hard to read. Print a label and the location with each one. A tiny helper using debug_backtrace() (explained below) can add the line number for you; the simplest version is just a label:

PHP
echo "cart before discount:\n";
var_dump($cart);

Dump and stop

Sometimes you want to see a value and stop right there, before later code changes it or redirects the browser. exit (or its alias die) ends the script:

PHP
var_dump($request);
exit;

Frameworks package this as a helper: Laravel and Symfony call it dd() ("dump and die") and also provide dump(), which prints nicely formatted, collapsible output in the browser. Just remember to delete these lines before committing; a forgotten exit in production is a classic outage.

Small helpers for types

When a bug is about types, these functions answer the question directly:

Function Example result Use it for
get_debug_type($x) int, string, null, App\User The clearest type name (PHP 8.0)
gettype($x) integer, string, NULL, object Older code; less precise
$object::class App\User The class of an object
spl_object_id($obj) 3 Whether two variables hold the same object
json_encode($x, JSON_PRETTY_PRINT) indented JSON Compact view of nested data

Reading error messages and stack traces

A good error message often tells you the answer outright, if you read all of it. Take this one:

TEXT
Fatal error: Uncaught TypeError: applyDiscount(): Argument #2 ($percent) must be of type int, string given, called in main.php on line 14 and defined in main.php:5

It names the function (applyDiscount()), the parameter (#2, $percent), what was expected (int), what arrived (string), the line of the call (14) and the line where the function is defined (5). The bug is on line 14, where a string is passed; line 5 is just where PHP noticed.

For exceptions thrown deeper in your code, the stack trace shows how execution got there. Run this example, which fails on purpose:

PHP Reading a stack trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first checkout prints Total: 9. The second prints Total: (echo outputs its first argument before it calls cartTotal()) and then stops with:

TEXT
Fatal error: Uncaught InvalidArgumentException: Not a price: '3,20' in main.php:7
Stack trace:
#0 main.php(16): parsePrice('3,20')
#1 main.php(23): cartTotal(Array)
#2 main.php(27): checkout(Array)
#3 {main}
  thrown in main.php on line 7

Read it like this:

  1. The first line says what and where: an InvalidArgumentException with the message Not a price: '3,20', created on line 7.
  2. Frame #0 is the most recent call: line 16 called parsePrice('3,20'). The argument is shown, which is the real clue: someone typed a comma as the decimal separator.
  3. The following frames go back in time: cartTotal() was called from line 23, checkout() from line 27, and is the top level of the script.

Arrays and objects are shown as Array and Object(ClassName) to keep traces short, and long strings are cut after 15 characters. In a real application, the frames in your own code are the interesting ones; skip over framework frames until you reach a file you wrote.

Where am I? debug_backtrace

debug_backtrace() returns the current call stack as an array, without throwing anything. Each frame has keys like function, line, file, class and args. It's useful for "who is calling this function?" questions, and for helpers that report where they were called from:

PHP A dump helper that knows its caller

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The dumps show [line 12] code = 'VIP25' and [line 18] percent = 25 for the first call, then code = 'spring10' and percent = 0 for the second. That points straight at the bug: coupon codes are compared case-sensitively, so a lowercase code gets no discount. (The fix is match (strtoupper($code ?? '')).)

DEBUG_BACKTRACE_IGNORE_ARGS skips copying the arguments, and the limit 1 returns only the frame of the immediate caller, which keeps the call cheap. To print the whole stack in trace format, call debug_print_backtrace(), or create an exception without throwing it and use (new Exception())->getTraceAsString().

Logging instead of printing

Printing doesn't work everywhere. In an API, a dump breaks the JSON; in a redirect, nobody sees it; in a queue worker, there's no browser at all. In those cases write to the error log with error_log(), and watch the log in a terminal while you reproduce the bug:

Terminal
# Follow the PHP log live (the path depends on your setup)
tail -f /var/log/php/app-errors.log

# Laravel apps log to storage/logs
tail -f storage/logs/laravel.log
PHP Writing debug lines to a log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The response stays clean JSON ({"shipping":14.3}), while the log records shippingCost(3.5 kg, FR) = 14.30. (The preg_replace() call only strips the timestamp so the output is the same on every run. header() does nothing on the command line; on a server it would set the content type.)

For anything you want to keep in production, use a proper PSR-3 logger like Monolog with levels (debug, info, warning, error), so you can switch noisy debug lines off without deleting them.

Step debugging with Xdebug

Dumping values works, but it's slow when you don't yet know where to look. A step debugger lets you pause the program at a line (a breakpoint), see every variable in scope, and then run one line at a time while watching values change. For PHP that's Xdebug, an extension that connects to your editor (PhpStorm, VS Code with the PHP Debug extension, and others). Xdebug isn't installed on our server, so this part is read-only.

A typical development setup in php.ini (or a file in conf.d/):

INI
zend_extension = xdebug
xdebug.mode = debug,develop
xdebug.start_with_request = trigger
xdebug.client_host = 127.0.0.1
xdebug.client_port = 9003
  • xdebug.mode = debug enables step debugging; develop adds nicer error output and an improved var_dump(). Other modes are coverage (code coverage for tests), profile and trace.
  • start_with_request = trigger only starts a debug session when you ask for one, via a browser extension ("Xdebug helper"), a XDEBUG_TRIGGER cookie or query parameter, or an environment variable on the command line. yes would debug every request, which makes everything slow.
  • Port 9003 is the default since Xdebug 3. Your editor listens there.

On the command line you start a session like this:

Terminal
XDEBUG_TRIGGER=1 php artisan app:import-orders

The workflow in the editor is the same everywhere: click in the gutter to set a breakpoint, start listening, trigger the request, and when execution pauses use step over (run this line), step into (go inside the function call), step out (finish this function) and continue. Conditional breakpoints ("pause only when $order->id === 1042") save a lot of time in loops.

Never enable Xdebug on a production server. Even when no debugger is connected, it slows PHP down considerably, and an open debug port is a security risk. Install it only in development, or in containers built for development.

Checking assumptions with assert

assert() states something that must be true at a certain point. If the condition is false, PHP throws an AssertionError. Assertions catch bugs close to their cause, instead of three functions later:

PHP assert catches a broken assumption

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first call prints 4. The second fails the rating check, and because no message was given, PHP uses the code itself as the message: assert($rating >= 1 && $rating <= 5). The third uses the custom message.

Assertions are a development tool. They're controlled by the zend.assertions setting, which can only be set in php.ini:

zend.assertions Effect
1 Assertions are compiled and checked (development; our editor uses this)
0 Compiled but skipped at run time
-1 Not compiled at all: zero cost (the production default)

Because they may be switched off, never use assert() to validate user input or anything else that must always be checked. assert(isset($_POST['email'])) silently disappears in production. Use an if with an exception for that, as in Form Validation. And never put code with side effects inside an assertion, such as assert($db->save($order)): with assertions off, the save never happens.

A debugging checklist

When you're stuck, work through these steps in order:

  1. Reproduce it. Find the smallest input that causes the bug. A bug you can trigger on demand is half solved.
  2. Read the whole error message, including the trace. Find the first frame in your own code.
  3. Check your assumptions with var_dump(): types, null, empty strings, array keys, letter case, extra spaces (var_dump() shows the string length, so string(6) "admin " gives away a trailing space).
  4. Divide and conquer. Dump a value halfway through. If it's already wrong, the bug is earlier; if it's right, it's later.
  5. Make sure all errors are visible. error_reporting(E_ALL) and display_errors on in development, or watch the log. A hidden warning is often the real cause.
  6. Explain the code out loud, line by line, to a colleague or a rubber duck. Saying "and here $total is the sum of..." is often when you notice it isn't.
  7. Write a test that reproduces the bug before fixing it, so it can never come back unnoticed. Testing PHP Code shows how.

Also run php -l file.php ("lint") to check a file for syntax errors without executing it; editors and CI pipelines do this automatically. Static analysers like PHPStan go further and find type bugs without running anything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You suspect $id holds the string "7" rather than the integer 7. Which call shows the difference?

    var_dump prints string(1) "7" for the string and int(7) for the integer. print_r and echo both just print 7, and %d converts the value to an integer anyway.
  2. 2. A trace shows #0 main.php(16): parsePrice(...) and #1 main.php(23): cartTotal(Array). What does frame #1 tell you?

    Frames go back in time. Frame #0 is the latest call (line 16 calling parsePrice), and frame #1 shows that line 23 called cartTotal, which contains line 16.
  3. 3. Why must you never write assert($user->save());?

    Assertions can be removed entirely. Any side effect inside them disappears with them, and so do input checks.
  4. 4. Which output does var_export(['ok' => true]) produce?

    var_export prints valid PHP code, here formatted over several lines. The second option is print_r, the third var_dump and the last json_encode.
  5. 5. Why is xdebug.start_with_request = trigger a better development default than yes?

    With yes, Xdebug tries to start a debug session on every request. With trigger, it waits for a cookie, query parameter or environment variable such as XDEBUG_TRIGGER.

Summary

  • Debugging is guess, evidence, narrow down. Start by looking at the actual values.
  • var_dump() shows types and lengths (use it when in doubt), print_r() is compact but hides false/null, var_export() prints PHP code. Pass true to print_r()/var_export() to get a string for logs.
  • get_debug_type(), ::class and spl_object_id() answer type and identity questions quickly. exit after a dump stops the script (frameworks call it dd()); remove it before committing.
  • Read error messages completely and stack traces from the top: frame #0 is the latest call; find the first frame in your own code.
  • debug_backtrace() returns the call stack as an array (use DEBUG_BACKTRACE_IGNORE_ARGS and a limit); debug_print_backtrace() prints it.
  • Where output can't be seen (APIs, redirects, workers), use error_log() and tail -f the log; use a PSR-3 logger for lasting log lines.
  • Xdebug provides breakpoints and stepping (mode debug, port 9003, start_with_request = trigger). Development only.
  • assert() throws AssertionError when an assumption is false; it's disabled in production (zend.assertions = -1), so never use it for input validation or side effects.

Next: Reading and Writing Files