A simple way to debug a php application in production mode

Useful function to output debug data in PHP

A simple way to debug a php application in production mode

A very useful debug function in PHP i like to use to print debug output to browser window. In some cases where i may not output the debug to browser window i use the same function to receive debug output in my email inbox.

We usually use print_r or var_dump to show debug output. This function uses print_r by default but one can use var_dump to show the output. This function was created to show the print_r output enclosed in <pre> tags. Later it was extended to show line number where print output was sought. Later var_dump and email options were added. This function has proved very good tool for me to debug php applications. I hope someone else might find it useful, thus sharing.

Here’s the function:

if(!function_exists('pr'))	{
	function pr($p, $func="print_r",$r=false)    {
		if(!function_exists($func))	{
			die("Debug function {$func} does not exist!");
		}
		if(!$func) $func='print_r';
		$bt = debug_backtrace();
		$caller = array_shift($bt);
		$file_line = "<strong>" . $caller['file'] . "(line " . $caller['line'] . ")</strong>\n";
		if(!$r)    { //if print
			echo '<pre>';
			print_r($file_line);
			$func($p);
			echo '</pre>';
		} else { //if return
			ob_start();
			echo '<pre>';
			print_r($file_line);
			$func($p);
			echo '<pre>';
			$d = ob_get_contents();
			ob_end_clean();
			if(filter_var($r, FILTER_VALIDATE_EMAIL)) {
				$headers = 'From: webmaster@example.com' . "\r\n" .
				'Reply-To: webmaster@example.com' . "\r\n" .
				'X-Mailer: PHP/' . phpversion();
				mail($r, 'Debug Output', $d, $headers);
			}
			return $d;
		}
	}
}

How to use:

To print simple output, where is $output is the output to be printed.

  • pr($output) ; //uses print_r by default enclosed in <pre> tags to print output
  • pr($output, “var_dump”); //prints output using var_dump enclosed in <pre> tags
  • pr($output, ”, true); //returns output ; uses print_r enclosed in <pre> tags
  • pr($output, “var_dump”, ‘your@domain.com’); //sends var_dump output enclosed in <pre> tags to email address supplied. Returns as well.
  • pr($output, ”, ‘your@domain.com’); //sends print_r output enclosed in <pre> tags to email address supplied. Returns as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>