[php] How do you debug PHP scripts?

How do you debug PHP scripts?

I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in PHPEclipse is also quite useful.

What is the best (in terms of fast and easy) way to debug in phpStorm or any other IDE?

This question is related to php eclipse debugging phpstorm xdebug

The answer is


The Interactive Stepthrough PHP Debugger implemented as a SAPI module which can give give you complete control over the environment without impacting the functionality or performance of your code. It aims to be a lightweight, powerful, easy to use debugging platform for PHP 5.4+ and it's shipped out-of-box with PHP 5.6.

Features includes:

  • Stepthrough Debugging
  • Flexible Breakpoints (Class Method, Function, File:Line, Address, Opcode)
  • Easy Access to PHP with built-in eval()
  • Easy Access to Currently Executing Code
  • Userland API
  • SAPI Agnostic - Easily Integrated
  • PHP Configuration File Support
  • JIT Super Globals - Set Your Own!!
  • Optional readline Support - Comfortable Terminal Operation
  • Remote Debugging Support - Bundled Java GUI
  • Easy Operation

See the screenshots:

PHP DBG - Stepthrough Debugging - screenshot

PHP DBG - Stepthrough Debugging - screenshot

Home page: http://phpdbg.com/

PHP Error - Better error reporting for PHP

This is very easy to use library (actually a file) to debug your PHP scripts.

The only thing that you need to do is to include one file as below (at the beginning on your code):


Then all errors will give you info such as backtrace, code context, function arguments, server variables, etc. For example:

PHP Error | Improve Error Reporting for PHP - screenshot of backtrace PHP Error | Improve Error Reporting for PHP - screenshot of backtrace PHP Error | Improve Error Reporting for PHP - screenshot of backtrace

Features include:

  • trivial to use, it's just one file
  • errors displayed in the browser for normal and ajaxy requests
  • AJAX requests are paused, allowing you to automatically re-run them
  • makes errors as strict as possible (encourages code quality, and tends to improve performance)
  • code snippets across the whole stack trace
  • provides more information (such as full function signatures)
  • fixes some error messages which are just plain wrong
  • syntax highlighting
  • looks pretty!
  • customization
  • manually turn it on and off
  • run specific sections without error reporting
  • ignore files allowing you to avoid highlighting code in your stack trace
  • application files; these are prioritized when an error strikes!

Home page: http://phperror.net/

GitHub: https://github.com/JosephLenton/PHP-Error

My fork (with extra fixes): https://github.com/kenorb-contrib/PHP-Error


If your system supports DTrace dynamic tracing (installed by default on OS X) and your PHP is compiled with the DTrace probes enabled (--enable-dtrace) which should be by default, this command can help you to debug PHP script with no time:

sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

So given the following alias has been added into your rc files (e.g. ~/.bashrc, ~/.bash_aliases):

alias trace-php='sudo dtrace -qn "php*:::function-entry { printf(\"%Y: PHP function-entry:\t%s%s%s() in %s:%d\n\", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }"'

you may trace your script with easy to remember alias: trace-php.

Here is more advanced dtrace script, just save it into dtruss-php.d, make it executable (chmod +x dtruss-php.d) and run:

#!/usr/sbin/dtrace -Zs
# See: https://github.com/kenorb/dtruss-lamp/blob/master/dtruss-php.d

#pragma D option quiet

    printf("%Y: PHP compile-file-entry:\t%s (%s)\n", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1));

    printf("%Y: PHP compile-file-return:\t%s (%s)\n", walltimestamp, basename(copyinstr(arg0)), basename(copyinstr(arg1)));

    printf("%Y: PHP error message:\t%s in %s:%d\n", walltimestamp, copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);

    printf("%Y: PHP exception-caught:\t%s\n", walltimestamp, copyinstr(arg0));

    printf("%Y: PHP exception-thrown:\t%s\n", walltimestamp, copyinstr(arg0));

    printf("%Y: PHP execute-entry:\t%s:%d\n", walltimestamp, basename(copyinstr(arg0)), (int)arg1);

    printf("%Y: PHP execute-return:\t%s:%d\n", walltimestamp, basename(copyinstr(arg0)), (int)arg1);

    printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);

    printf("%Y: PHP function-return:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);

    printf("%Y: PHP request-shutdown:\t%s at %s via %s\n", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1), copyinstr(arg2));

    printf("%Y, PHP request-startup:\t%s at %s via %s\n", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1), copyinstr(arg2));

Home page: dtruss-lamp at GitHub

Here is simple usage:

  1. Run: sudo dtruss-php.d.
  2. On another terminal run: php -r "phpinfo();".

To test that, you can go to any docroot with index.php and run PHP builtin server by:

php -S localhost:8080

After that you can access the site at http://localhost:8080/ (or choose whatever port is convenient for you). From there access some pages to see the trace output.

Note: Dtrace is available on OS X by default, on Linux you probably need dtrace4linux or check for some other alternatives.

See: Using PHP and DTrace at php.net


Alternatively check for SystemTap tracing by installing SystemTap SDT development package (e.g. yum install systemtap-sdt-devel).

Here is example script (all_probes.stp) for tracing all core PHP static probe points throughout the duration of a running PHP script with SystemTap:

probe process("sapi/cli/php").provider("php").mark("compile__file__entry") {
    printf("Probe compile__file__entry\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
probe process("sapi/cli/php").provider("php").mark("compile__file__return") {
    printf("Probe compile__file__return\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
probe process("sapi/cli/php").provider("php").mark("error") {
    printf("Probe error\n");
    printf("  errormsg %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
probe process("sapi/cli/php").provider("php").mark("exception__caught") {
    printf("Probe exception__caught\n");
    printf("  classname %s\n", user_string($arg1));
probe process("sapi/cli/php").provider("php").mark("exception__thrown") {
    printf("Probe exception__thrown\n");
    printf("  classname %s\n", user_string($arg1));
probe process("sapi/cli/php").provider("php").mark("execute__entry") {
    printf("Probe execute__entry\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
probe process("sapi/cli/php").provider("php").mark("execute__return") {
    printf("Probe execute__return\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
probe process("sapi/cli/php").provider("php").mark("function__entry") {
    printf("Probe function__entry\n");
    printf("  function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
probe process("sapi/cli/php").provider("php").mark("function__return") {
    printf("Probe function__return: %s\n", user_string($arg1));
    printf(" function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
probe process("sapi/cli/php").provider("php").mark("request__shutdown") {
    printf("Probe request__shutdown\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
probe process("sapi/cli/php").provider("php").mark("request__startup") {
    printf("Probe request__startup\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));


stap -c 'sapi/cli/php test.php' all_probes.stp

See: Using SystemTap with PHP DTrace Static Probes at php.net

Output buffering is very useful if you don't want to mess up your output. I do this in a one-liner which I can comment/uncomment at will

 ob_start();var_dump(); user_error(ob_get_contents()); ob_get_clean();

I use Netbeans with XDebug and the Easy XDebug FireFox Add-on

The add-on is essential when you debug MVC projects, because the normal way XDebug runs in Netbeans is to register the dbug session via the url. With the add-on installed in FireFox, you would set your Netbeans project properties -> Run Configuratuion -> Advanced and select "Do Not Open Web Browser" You can now set your break points and start the debugging session with Ctrl-F5 as usual. Open FireFox and right-click the Add-on icon in the right bottom corner to start monitoring for breakpoints. When the code reaches the breakpoint it will stop and you can inspect your variable states and call-stack.

+1 for print_r(). Use it to dump out the contents of an object or variable. To make it more readable, do it with a pre tag so you don't need to view source.

echo '<pre>';

Also var_dump($thing) - this is very useful to see the type of subthings

I've used the Zend Studio (5.5), together with Zend Platform. That gives proper debugging, breakpoints/stepping over the code etc., although at a price.

1) I use print_r(). In TextMate, I have a snippet for 'pre' which expands to this:

echo "<pre>";
echo "</pre>";

2) I use Xdebug, but haven't been able to get the GUI to work right on my Mac. It at least prints out a readable version of the stack trace.

The integrated debuggers where you can watch the values of variable change as you step through code are really cool. They do, however, require software setup on the server and a certain amount of configuration on the client. Both of which require periodic maintenance to keep in good working order.

A print_r is easy to write and is guaranteed to work in any setup.

XDebug is essential for development. I install it before any other extension. It gives you stack traces on any error and you can enable profiling easily.

For a quick look at a data structure use var_dump(). Don't use print_r() because you'll have to surround it with <pre> and it only prints one var at a time.

<?php var_dump(__FILE__, __LINE__, $_REQUEST); ?>

For a real debugging environment the best I've found is Komodo IDE but it costs $$.

There are many PHP debugging techniques that can save you countless hours when coding. An effective but basic debugging technique is to simply turn on error reporting. Another slightly more advanced technique involves using print statements, which can help pinpoint more elusive bugs by displaying what is actually going onto the screen. PHPeclipse is an Eclipse plug-in that can highlight common syntax errors and can be used in conjunction with a debugger to set breakpoints.

display_errors = Off
error_reporting = E_ALL 
display_errors = On

and also used


Xdebug and the DBGp plugin for Notepad++ for heavy duty bug hunting, FirePHP for lightweight stuff. Quick and dirty? Nothing beats dBug.

Komodo IDE works well with xdebug, even for the remore debugging. It needs minimum amount of configuration. All you need is a version of php that Komodo can use locally to step through the code on a breakpoint. If you have the script imported into komodo project, then you can set breakpoints with a mouse-click just how you would set it inside eclipse for debugging a java program. Remote debugging is obviously more tricky to get it to work correctly ( you might have to map the remote url with a php script in your workspace ) than a local debugging setup which is pretty easy to configure if you are on a MAC or a linux desktop.

print_r( debug_backtrace() );

or something like that :-)

PhpEdit has a built in debugger, but I usually end up using echo(); and print_r(); the old fashioned way!!

i use zend studio for eclipse with the built in debugger. Its still slow compared to debugging with eclipse pdt with xdebug. Hopefully they will fix those issues, the speed has improved over the recent releases but still stepping over things takes 2-3 seconds. The zend firefox toolbar really makes things easy (debug next page, current page, etc). Also it provides a profiler that will benchmark your code and provide pie-charts, execution time, etc.

Nusphere is also a good debugger for php nusphere

This is my little debug environment:

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'assert_callcack');

function assert_callcack($file, $line, $message) {
    throw new Customizable_Exception($message, null, $file, $line);

function error_handler($errno, $error, $file, $line, $vars) {
    if ($errno === 0 || ($errno & error_reporting()) === 0) {

    throw new Customizable_Exception($error, $errno, $file, $line);

function exception_handler(Exception $e) {
    // Do what ever!
    echo '<pre>', print_r($e, true), '</pre>';

function shutdown_handler() {
    try {
        if (null !== $error = error_get_last()) {
            throw new Customizable_Exception($error['message'], $error['type'], $error['file'], $error['line']);
    } catch (Exception $e) {

class Customizable_Exception extends Exception {
    public function __construct($message = null, $code = null, $file = null, $line = null) {
        if ($code === null) {
        } else {
            parent::__construct($message, $code);
        if ($file !== null) {
            $this->file = $file;
        if ($line !== null) {
            $this->line = $line;

Xdebug, by Derick Rethans, is very good. I used it some time ago and found it was not so easy to install. Once you're done, you won't understand how you managed without it :-)

There is a good article on Zend Developer Zone (installing on Linux doesn't seem any easier) and even a Firefox plugin, which I never used.

I often use CakePHP when Rails isn't possible. To debug errors I usually find the error.log in the tmp folder and tail it in the terminal with the command...

tail -f app/tmp/logs/error.log

It give's you running dialog from cake of what is going on, which is pretty handy, if you want to output something to it mid code you can use.


This can usually give you a good idea of what is going on/wrong.

PhpEd is really good. You can step into/over/out of functions. You can run ad-hoc code, inspect variables, change variables. It is amazing.

Usually I find create a custom log function able to save on file, store debug info, and eventually re-print on a common footer.

You can also override common Exception class, so that this type of debugging is semi-automated.

Manual debugging is generally quicker for me - var_dump() and debug_print_backtrace() are all the tools you need to arm your logic with.

You can use Firephp an add-on to firebug to debug php in the same environment as javascript.

I also use Xdebug mentioned earlier for profiling php.

In all honesty, a combination of print and print_r() to print out the variables. I know that many prefer to use other more advanced methods but I find this the easiest to use.

I will say that I didn't fully appreciate this until I did some Microprocessor programming at Uni and was not able to use even this.

In a production environment, I log relevant data to the server's error log with error_log().

Well, to some degree it depends on where things are going south. That's the first thing I try to isolate, and then I'll use echo/print_r() as necessary.

NB: You guys know that you can pass true as a second argument to print_r() and it'll return the output instead of printing it? E.g.:

echo "<pre>".print_r($var, true)."</pre>";

I use Netbeans with XDebug. Check it out at its website for docs on how to configure it. http://php.netbeans.org/

For the really gritty problems that would be too time consuming to use print_r/echo to figure out I use my IDE's (PhpEd) debugging feature. Unlike other IDEs I've used, PhpEd requires pretty much no setup. the only reason I don't use it for any problems I encounter is that it's painfully slow. I'm not sure that slowness is specific to PhpEd or any php debugger. PhpEd is not free but I believe it uses one of the open-source debuggers (like XDebug previously mentioned) anyway. The benefit with PhpEd, again, is that it requires no setup which I have found really pretty tedious in the past.

Depending on the issue I like a combination of error_reporting(E_ALL) mixed with echo tests (to find the offending line/file the error happened in initally; you KNOW it's not always the line/file php tells you right?), IDE brace matching (to resolve "Parse error: syntax error, unexpected $end" issues), and print_r(); exit; dumps (real programmers view the source ;p).

You also can't beat phpdebug (check sourceforge) with "memory_get_usage();" and "memory_get_peak_usage();" to find the problem areas.

The most of bugs can be found easily by simply var_dumping some of key variables, but it obviously depends on what kind of application you develop.

For a more complex algorithms the step/breakpoint/watch functions are very helpful (if not necessary)

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to debugging

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug

Examples related to phpstorm

Difference between WebStorm and PHPStorm Cannot ignore .idea/workspace.xml - keeps popping up JetBrains / IntelliJ keyboard shortcut to collapse all methods Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins? Word wrapping in phpstorm How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203) How to make phpstorm display line numbers by default? How do you debug PHP scripts?

Examples related to xdebug

Check if xdebug is working How to get xdebug var_dump to show full object/array How to disable XDebug Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP Increasing nesting function calls limit How do you debug PHP scripts?