PhpToolCase
Api Documentation Version 0.9.2
Debugger & Logger Component (PtcDebug)

Introduction

The goal of this class is to ease the process of debugging php scripts. The class uses a floating panel at the top right of the page. There are also a couple of features that can fix security issues with the php default error handler. All class properties and methods are static because it's required to let them work on script shutdown when FATAL error occurs.

Main Features:

  • Shows globals vars ($GLOBALS, $_POST, $_GET, $_COOKIE ...)
  • Shows php version and loaded extensions
  • Can replace php built in error handler
  • Logs sql queries
  • Can Catch exceptions
  • Inspects variables for changes
  • Function calls tracing
  • Code coverage analysis to check which lines of script where executed
  • Monitors execution time
  • Dumps all types of variable
  • Files inspector built-in, with code highlighter to view source code
  • Sends messages to js console to debug ajax requests ("Chrome Browser" only)
  • Can search files for a string recursively



Getting Started

The PtcDebug component works right out of the box, by calling the method PtcDebug::load():

// include the PtcDebug class
require_once( 'PtcDebug.php' );
// turn on the debug, should be passed in the url
$_GET['debug']=true;
// initialize the class

This will initialize the component, but keep in mind that there are more features that can be configured on initialization.
The followig paragraph will explain all possible options that can be passed to the class when the method PtcDebug::load( ) is called.


Class Options

This is the full list of options available on intialization, stored in PtcDebug::$_defaultOptions property:

$_defaultOptions = array
(
'url_key' => 'debug' , // the key to pass to the url to turn on debug
'url_pass' => 'true' , // the pass to turn on debug
'replace_error_handler' => true , // replace default php error handler
'error_reporting' => E_ALL , // error reporting flag
'catch_exceptions' => true , // sets exception handler to be this class method
'check_referer' => false , // check referer for key and pass ( good for ajax debugging )
'die_on_error' => true , // die if fatal error occurs ( with this class error handler )
'debug_console' => false , // only for Chrome,show messages in console ( phpConsole needed )
'allowed_ips' => null , // restrict access with ip's
'session_start' => false , // start session for persistent debugging
'show_interface' => true , // show the interface ( false to debug in console only )
'set_time_limit' => null , // set php execution time limit
'memory_limit' => null , // set php memory size
'show_messages' => true , // show messages panel
'show_globals' => true , // show global variables in vars panel
'show_sql' => true , // show sql panel
'show_w3c' => true, // show the w3c panel
'minified_html' => true , // compress html for a lighter output
'trace_depth' => 10 , // maximum depth for the backtrace
'max_dump_depth' => 6 , // maximum depth for the dump function
'panel_top' => '0px' , // panel top position
'panel_right' => '0px' , // panel right position
'default_category' => 'General' , // default category for the messages
'enable_inspector' => true , // enable variables inspector, use declare(ticks=n); in code block
'code_coverage' => true, // enable code coverage analysis, use "full" to start globally
'trace_functions' => true, // enable function calls tracing, use "full" to start globally
'exclude_categories' => array( 'Event Manager' , 'Autoloader' ) // exclude categories from the output
);

The following sections will describe these options in details.

url_key

To show the interface we use a "$_GET" parameter in the url (see url_pass), and to turn it off the same parameter + "_off" can be used. The default key is "debug" and should be changed to something else!

Default value: debug (string)

Note
The default value of this option, should be changed under production environment.

url_pass

The value to pass in the url (see url_key), the default value is "true" and should be changed to something else!

Default value: true (string)

Note
The default value of this option, should be changed under production environment.

replace_error_handler

Replaces the default php error handler to show php errors in the debug messages panel.

Default value: true (bool)


error_reporting

This options controls the error_report level of your application.

Default value: E_ALL (constant)


catch_exceptions

This options set to "true", can catch uncaught exceptions and log them to the messages panel.

Default value: true (bool)


check_referer

This option, if set to "true", will check for the url_key and url_pass with the referer if any. This is quite usefull to debug ajax scripts with the show_interface option set to "false", and the debug_console set to "true".

Default value: false (bool)


die_on_error

Set this option to false to continue if fatal error occurs, keep in mind that this will only work with the replace_error_handler option set to "true".

Default value: true (bool)


debug_console

Only for Chrome Browser, with php-console addon installed. This feature is very usefull to debug ajax requests.

See Ajax Debugging for more information and detailed usage.

Default value: false (bool)


allowed_ips

To restrict access use this option to pass an ip or an array of ip's, and only the allowed ip's will be able to turn on/off the debug interface.

Default value: null (string|array)

Note
It is advised to use this option under production environment.

session_start

For persistent debugging, set this option to "true", and the class will try to store the url_key and url_pass in a "$_SESSION" var. You will need to use url_key + "_off" to hide the interface.

Default value: false (bool)

Note
This option will only work if the method PtcDebug::load( ) is called at very start of your application / website.

show_interface

This option, if set to "false", does not show the floating panel. It is usefull to send messages to console only with the option debug_console set to "true".

See Ajax debugging (chrome only) for more details over this setup.

Default value: true (bool)


set_time_limit

Sets the php global execution time limit.

Default value: null (float)


memory_limit

Sets memory limit for php.

Default value: null (float)


show_messages

Controls if the messages panel will be shown, if set to "false" the interface will not show this panel and will be faster to load. This option can be turned on and off with the "$_GET" parameter "hidepanels" in the url.

see Hiding Panels for more information about this option.

Default value: true (bool)


show_globals

Controls if the "$GLOBALS" variable will be shown in the vars panel, if set to "false" the interface will not show the "$GLOBALS" and will be faster to load. This option can be turned on and off with the "$_GET" parameter "hidepanels" in the url.

see Hiding Panels for more information about this option.

Default value: true (bool)


show_sql

This option controls if the sql panel will be shown, if set to "false" the interface will not show this panel and will be faster to load. This option can be turned on and off with the "$_GET" parameter "hidepanels" in the url.

see Hiding Panels for more information about this option.

Default value: true (bool)


show_w3c

This option controls if the w3c validator panel will be shown, if set to "false" the interface will not show this panel and will be faster to load. This option can be turned on and off with the "$_GET" parameter "hidepanels" in the url.

see Hiding Panels for more information about this option.

Default value: true (bool)

Note
It is preferred to disable the w3c panel when working offline.

minified_html

By default the html output of the class is compressed. To print the output uncompressed set minified_html to "false".

Default value: true (bool)

Note
It is preferred to disable the w3c panel when working offline.

trace_depth

This option sets a depth limit for the backtrace. Increase it if you think that the backtrace is leaving out files.

Default value: 10 (float)


max_dump_depth

This option sets the maximum depth when dumping variables to prevent recursion. If maximum depth is reached, the message "**MAX DEPTH REACHED**" will be shown. Increase it if you need a higher depth.

Default value: 6 (float)


panel_top

This option sets the top position in pixels for the floating panel, change it to lower the panel.

Default value: 0px (string)


panel_right

This option sets the right position in pixels for the floating panel, change it to move the panel more to the left.

Default value: 0px (string)


default_category

The default category for the log/sql messages.

Default value: General (string)


enable_inspector

This option, enables the variable inspector, which can be used to watch if a given variable has changed. The backtrace will be more precise if the PtcDebug::watch( ) method is used inside a "declare(ticks=n){}" code block, instead of relying on the ticks declaration present at the beginning of the PtcDebug class file.

See Inspecting Variable Changes for example usages.

Default value: true (bool)


code_coverage

This option turns on/off the code coverage analisys engine to check which lines of code where executed. Set this option to "full" to check all your application.

See Code Coverage Analysis for example usages.

Default value: true (bool|string)

Note
On a large applcation setting this option to "full" will slow down code execution.

trace_functions

This option turns on/off the function calls tracing engine to trace function calls and passed arguments of your application. Set this option to "full" to check all your application.

See Function Calls Tracing for example usages.

Default value: true (bool|string)

Note
On a large applcation setting this option to "full" will slow down code execution.

exclude_categories

This option controls categories that should be discarded from the log. Quite usefull to exclude categories making the output faster to load.
Set this option to "null" to show all categories.

Default value: array( 'Event Manager' , 'Autoloader' ) (mixed)


Logging Data

The PtcDebug component offers many ways to log data, the next paragraphs will demostrate the various possibilities.

Logging Messages

To send data to the messages panel is quite simple, just use the PtcDebug::bufferLog( ) method:

// logging a message
PtcDebug::bufferLog( 'just a message' );
// logging a variable with a statement
$var = 'something';
PtcDebug::bufferLog( $var , 'testing a variable' );
// logging an array to the message panel with a different category
$array = array( 'key' => 'value' , 'key1' => 'value1' );
PtcDebug::bufferLog( $array , 'testing an array' , 'new category' );

Logging Sql Queries

To log sql queries use the PtcDebug::bufferSql( ) method:

// some sql query
$sql = 'select from where something';
// leaving the first parameter empty
PtcDebug::bufferSql( '' , $sql);



Execution Timing

The class allows to time execution for php code and sql queries. The following sections will give examples on how this can be done.

Timing Loops

To check how long things take to execute you can use the PtcDebug::stopTimer( ) method:

// starts the timer automatically when bufferLog( ) and bufferSql( ) are called
PtcDebug::bufferLog( '' , 'timing a loop' );
$a = array( );
for( $i = 0; $i < 100; $i++ ){ $a[ ] = $i; }
// using the reference to attach the execution time to the buffer
PtcDebug::stopTimer( 'timing a loop' );

To attach the result of the loop to the message, use the PtcDebug::addToBuffer( ) method:

// attaching the result of the loop to the message
PtcDebug::addToBuffer( 'timing a loop' , $a );

See Attaching Data To Messages for details over the PtcDebug::addToBuffer( ) method.

Timing Sql Queries

To check how long a query takes to execute you can use the PtcDebug::stopTimer( ) method:

// some sql query, will be used as reference
$sql = 'select from where something';
// leaving the first parameter empty, can be added later with the query result
PtcDebug::bufferSql( '' , $sql );
// executing the query here
// stop timer, the query is used as reference

To attach the result of the query to the message, use the add_to_log() function:

// attaching the result to the message based on the reference
PtcDebug::addToBuffer( $sql , $sql_result );

See Attaching Data To Messages for details over the PtcDebug::addToBuffer( ) method.


Replacing Error Handler

The method PtcDebug::setErrorHandler() is used to force the replacement of the built in php error handler even if the debug panel is not shown (see replace_error_handler). This is usefull for production environment, for the simple reason that if an error occurs the user will not see information about the error. This method could also be used with the parameter set to "false", so that if fatal error occurs, script execution will still continue.

// replace php built in error handler
// replace php built in error handler and continue execution if fatal error occurs
Note
Keep in mind that if you expect the script to die on error, this parameter should be left set to "true" (see die_on_error).

Inspecting Variable Changes

To check if a given variable has changed, the method PtcDebug::watch() with the option enable_inspector set to "true" can be used:

// declaring a ticks block to watch when a variable changes
declare(ticks=1)
{
$var='some test';
// passing the variable without the "$" symbol
PtcDebug::watch( 'var' );
// the variable changed
$var='some new value';
}
Note
Declaring ticks in a code block instead of relying on the declaration present at the to of the class will make the backtrace more accurate.

Code Coverage Analysis

The code coverage analysis tool can check which lines of code where executed in your application, included files will be added to the report aswell.

To use this features, the methods PtcDebug::startCoverage( ) and PtcDebug::stopCoverage( ) can be used:

// starting the code coverage analysis
// executing php code, as many lines as you like
// stopping the code coverage analysis
Note
If PtcDebug::stopCoverage( ) is not used, the analysis will go on till the end of execution of the application, and a new analysis cannot be started.
This is equivalent to using the option code_coverage set to "full".

Function Calls Tracing

The PtcDebug class is also capable of tracing function calls, creating a report showing the backtrace and arguments passed to each function call made in your application.

To use this feature, the methods PtcDebug::startTrace( ) and PtcDebug::stopTrace( ) can be used:

// starting the function calls analysis
// executing php code, as many lines as you like
// stopping the function calls analysis
Note
If PtcDebug::stopTrace( ) is not used, the analysis will go on till the end of execution of the application, and a new analysis cannot be started.
This is equivalent to using the option trace_functions set to "full".

Attaching Data To Messages

Data can be attached to a message after PtcDebug::bufferLog( ) and PtcDebug::bufferSql() methods are called, with the PtcDebug::addToBuffer( ) method. This is quite usefull if you are timing the execution of some code or a database query. The parameter "$reference" is the equivalent of the "$statement" parameter for PtcDebug::bufferLog( ) or PtcDebug::bufferSql() methods which should be called before PtcDebug::addToBuffer( ).

See Execution Timing for practical examples.


Inspecting Source Code

The PtcDebug class has a built-in engine for reading source code. This option is automatically available if session_start() is used, the file names in the panels will have an anchor that will open a popup window with the content of the file and the highlighted line of code if any.


Searching For A String Recursively

The PtcDebug class has a built-in engine for searching for a string recursively inside a given path. This option is automatically available if session_start() is used, the file analysis panel will have a form that will open a popup with the search results upon submission.


Hiding Panels

To load the interface faster, panels that are not required can be hidden. This can be done either by using the options available on initialization (see show_messages, show_globals, show_sql, show_w3c) or by sending the "$_GET" parameter "hidepanels" in the url.

These are all the possibile options for the "hidepanels" parameter:

  • sql (hides the sql panel)
  • globals (hides the global variables in the vars panel)
  • msg (hides the messages panel)
  • w3c (hides the w3c validator panel)
  • all (uses all options above)
  • none (shows all panels)
Note
This parameter accepts multiple values separated by coma, Ex: sql,globals.

Setup Examples

The following sections will demonstrate 3 different setup examples depending on the circumstances.

Development / Testing Environment

This example,demostrates how to configure and load the interface under testing environment:

require_once( 'PtcDebug.php' );
// turn on the debug
$_GET[ 'debug' ] = true;
// turn off debug
//$_GET['debug_off']=true;
// making the floating panel persistent
$debug_options = array
(
'session_start' => true,
);
// loading the component
PtcDebug::load( $debug_options );

Production Environment

This example demostrates how to configure and safely load the interface under production environment:

require_once( 'PtcDebug.php' );
// replace php built in error handler and continue execution if fatal error occurs
$debug_options = array
(
'url_key' => 'someKey',
'url_pass' => 'somePass', // use a complicated string!
'replace_error_handler' => false, // has been replaced already
'allowed_ips' => array(1.2.3.4,2.3.4.5), // array of ip's to secure the floating panel
);
// loading the component
PtcDebug::load( $debug_options );

Ajax Debugging

This example demostrates how to configure and show the buffer messages in the "Chrome Browser" js console, which is particularly usefull to debug ajax scripts. Keep in mind that this setup needs phpConsole class and the "Chorme Browser" addOn installed to work. Make sure you have downloaded the phpConsole class from the repository, and install the Chrome Browser addOn before starting to use this class to send messages to the console.

require_once( 'PtcDebug.php' );
$debug_options = array
(
'replace_error_handler' => true, // replace error handler
'die_on_error' => false, // continue if fatal error
'debug_console' => true, // send buffer to js console
'check_referer' => true, // check if referer has key and pass.
'show_interface' => false // don't show interface, only console
);
// loading the component
PtcDebug::load( $debug_options );