PHP Debugging with Xdebug
In this page:
What is Xdebug?
Xdebug is a PHP extension that adds debugging, profiling, and code-analysis capabilities the language doesn't have on its own, and is close to a standard tool for serious PHP development.
Example: What is Xdebug?
<?php
echo extension_loaded('xdebug') ? "Xdebug is loaded" : "Xdebug not installed";
echo "\nAdds debugging, profiling, and code analysis to PHP";
?>
Login to try C/C++/Java/PHP code in the editor
Stack Traces and Var Dumps
With Xdebug enabled, PHP's normal error output gets replaced with much richer messages -- including a full stack trace and nicely formatted variable dumps -- that make tracking down the source of a bug considerably faster.
Example: Stack Traces and Var Dumps
<?php
function level3() { throw new Exception("Something broke"); }
function level2() { level3(); }
function level1() { level2(); }
try {
level1();
} catch (Exception $e) {
echo $e->getTraceAsString();
}
?>
Login to try C/C++/Java/PHP code in the editor
Step Debugging
Step debugging lets you set a breakpoint in your IDE, run the script, and have execution pause exactly there so you can inspect variables and step through subsequent lines one at a time instead of guessing from logs.
Example: Step Debugging
<?php
$x = 5;
$y = 10;
$sum = $x + $y; // set a breakpoint here in your IDE to inspect $x and $y
echo $sum;
?>
Login to try C/C++/Java/PHP code in the editor
Code Coverage
Code coverage tracking records which lines actually executed during a test run, revealing gaps in your test suite -- code paths nobody is testing at all.
Example: Code Coverage
<?php
function isEven($n) {
if ($n % 2 === 0) {
return true;
}
return false; // a test suite might never exercise this line
}
echo isEven(4) ? "even" : "odd";
?>
Login to try C/C++/Java/PHP code in the editor
Performance Profiling
Xdebug's profiler records how much time and memory each function call consumes, producing a file you can load into a tool like KCachegrind to visually spot the actual bottleneck instead of guessing.
Example: Performance Profiling
<?php
function slowFunction() {
for ($i = 0; $i < 100000; $i++) {}
}
$start = microtime(true);
slowFunction();
echo "Took " . round(microtime(true) - $start, 4) . "s -- a profiler shows exactly where time goes";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: