(redirected from Main.HowToSetUpForDebuggingInPHP)
On this page... (hide)
Debugging PHP can be a major pain. If you're not using something like Xdebug, typically, debugging PHP is done via printing out variables and state information to the browser as your application is running. Turning debugging on and off is sometimes a major pain. I've devised scheme to make it much simpler.
Also, see the section on php.net about debugging.
Using the query string or post vars
My scheme uses the query string or post vars on any PHP script call to include the parameter debug=true. Thus to call a script and turn on debugging, one could use http://www.example.com/myscript.php?debug=true.
To set this up, I include the following in my config.inc.php file, which gets called at the beginning of every script in the application:
- /**
- * set up some strings to identify debug information in output
- */
- define('DEBUGPREFIX','<p class="debug">');
- define('DEBUGSUFFIX','</p>');
- /**
- * Setting some operating values from the query string
- */
- $additional_query_parms = Array();
- /**
- * Allow debug option to be set on the query string or post value, or a server environment variable (useful for command line stuff)
- **/
- if ((isset($_REQUEST['debug']) &&
- strtolower($_REQUEST['debug']) == 'true') ||
- (isset($_SERVER['DEBUG']) &&
- strtolower($_SERVER['DEBUG']) == 'true')) {
- $GLOBALS['debug']=TRUE;
- error_reporting(-1); //report every error
- ini_set('display_errors',TRUE); // send error messages to output
- ini_set('display_startup_errors',TRUE); // send startup messages to output
- $additional_query_parms['debug'] = 'true'; // ensure debugging is carried through with subsequent redirects and url calls
- } else {
- $GLOBALS['debug']=FALSE;
- }
As you can see, this set the global debug to true or false depending on the existence and value of the debug parameter on either the query string or from the post data or from the environment. The $additional_query_parms is an array to keep track of any additional query or post info that might be needed to add to redirect urls or urls in the emitted html code, thus allowing the debug flag to be set once and perpetuated to other script calls.
Another way to do this is to use a session variable to set the debug state, which will be carried over to every other script called within the same session. See Setting Up Session In PHP? for more details on how to use session variables.
Then, I set up a couple of functions (in a file I usually call functions.inc.php which gets included by config.inc.php in every script):
- /**
- * debug function - print a message if DEBUG === TRUE
- **/
- function debug($msg,$var='',$file='',$line='')
- {
- if (!$GLOBALS['debug']) return;
- $out = '';
- if (defined('DEBUGPREFIX') $out .= DEBUGPREFIX;
- $out .= "DEBUG";
- if (!empty($file) $out .= ' in '.$file;
- if (!empty($line) $out .= '@'.$line.": ";
- $out .= $msg.PHP_EOL;
- if (!empty($var) {
- $out .= "<pre>" . (!is_scalar($var) ? htmlentities(print_r($var,true)) : htmlentities($var)) . "</pre>" . PHP_EOL;
- }
- if (defined('DEBUGSUFFIX') $out .= DEBUGSUFFIX;
- error_log($out); // send message to syslog
- echo $out;
- }
Notice that the string is output wrapped by DEBUGPREFIX and DEBUGSUFFIX defined above to make it apparent this is debugging code. (The constants are typically defined in the config.inc.php file before the include of function.inc.php.)
debug() let's you print out a string of info with an optional variable, as well as the current file and line number. If the variable is an array, it gets formatted by the print_r().
To call debug, place a line similar to:
- debug("The current value of var is:",$var,__FILE__,__LINE__);
The function takes care of checking whether the DEBUG flag is set on, so you can simply embed the debugging calls into your script and forget about them. I tend to leave the debugging calls in until I've thoroughly tested the code. Code under development seems to work better with debugging things left in.
Thus, in many cases, I have something like the following at the front of every script:
- debug("\$_GET: ",$_GET);
- debug("\$_POST: ",$_POST);
Just to see what is getting passed into each script. If a configuration file gets included early, I'll usually just throw those two lines in there.
The problem with redirects when debugging
Oftentimes, one script will do some processing and then redirect to another script to finish up and display the actual results. When debugging, you don't always want this to happen so you can see what's going on on the page you're working on without losing the potential debugging out when a page redirects.
Thus, I've come up with the following function to handle those situations:
- /**
- * perform a redirect to the indicated url $u, applying other parameters as needed.
- *
- * @return none - will either redirect or exit
- * @author Tamara Temple
- **/
- function do_redirect($u)
- {
- if (!isset($u)) $u = DEFAULT_REDIRECT;
- $u = buildredirect($u);
- debug("Redirect: \$u=$u");
- if (!$GLOBALS['debug']) header("Location: $u"); else exit("<p><a href='$u'>Redirect to $u</a></p>");
- }
The effect of the above function is to create a redirect string then when debugging, print out the redirect string and a link to the redirect and exit. When not debugging, the redirect happens the normal way.
The buildredirect() function is a nice utility for creating useful redirects with additional query attributes. See HandlingRedirectsInPHP.
Advanced Debugging Features
The above is great for doing rudimentary debugging in a straight-forward fashion. Sometimes, though, you want to do things a bit more precisely to keep things neat within an application.
As such, I've written a debug class script (Attach:class.debug.phps Δ that can be included in the application to handle debugging in a more interesting fashion.
Place this into a common include file, such as config.inc.php:
- include_once('class.debug.php');
- $dbg = new Debug();
By default, this will turn debugging on, use HTML in debug output, use the standard error logging facility, emit output directly, and use a standard prefix and suffix for the debugging output.
Then, to make debug statements, insert the line:
- $dbg->p("Debug message",$var,__FILE__,__LINE__);
where you want your debug output to appear.
The class contains a number of methods, which are documented in the source file.
| Tags: | Categories: HowTos |
Recent Changes |
Printable View |
Page History |
Edit Page
Page last modified on April 17, 2012, at 08:59 PM by ImportText?