Debugging PHP in a floating javascript window

Zvonko wrote an interesting article on codeforest: Debugging PHP in browser’s Javascript console.

Debugging tools are a natural feature of frameworks like Zend, Symfony and others, but there are cases where it is not practical to use such a framework. This is where simple debugging tools can be handy.

Zvonko’s idea is that the PHP developper can output debugging information without altering the layout of his page. This is achieved by printing to the javascript console, which is accessible in Chrome by doing CTR-Sh-J, then ESC. Not clear how that works in other browsers.

I offer an alternative: printing to a javascript dialog box. This means you will not need to go in the guts of your browser: the debugging info will appear on the side of your HTML page, and can be hidden if needed. I use jquery but it’s possible that writing it in javascript from scratch is not that hard.

My class is called JSDebugger. Usage is as follows:


$debug = new JSDebugger();
// here you want to display stuff to the debugging window:
$debug->debug( "Value of x is $x" );

The code below is not meant to work out of the box but let me know if I need to make it more generic. The purpose is just to show the idea.

<?php

require( "HTML.php");

// you may want to replace this with wherever you put your jquery libraries
function script($name)
{
	$Map = Array(
					'jquery' 	=> 'jquery.js',
					'jquery-ui' => 'jquery-ui-1.8.9.custom.js'
				);
	
	$script = $Map[$name];	
	?>
	
<script type="text/javascript" src="javascripts/<?php print $script ?>"></script>

<?php 
}

class JSDebugger {

	function __construct() 
	{
            // include jquery libraries
	    script('jquery');
	    script('jquery-ui');
	    ?>
	    
	<link rel="stylesheet" href="stylesheets/themes/start/jquery.ui.all.css"> 
	    
	<style>
	.ui-dialog 	{ background: #eeeeee; }
	#debuglog 	{ font-size: 0.4em; }
	.ui-dialog-title { font-size: 0.6em; 	}
	</style>

	    <script type="text/javascript">
	
		myvar = "";
		function init()
		{
		
		    $("#debuglog")
		    	.dialog( {
					position: [ "right", "top" ],
					title: "Debug console",
		    	})
		}
	
		$(document).ready(init);
		
	    </script>
	    <div id='debuglog'></div>
	    
	    <?php 
	}
	
	function debug($message, $type = LOG) 
	{
		$bt = debug_backtrace();
		$bt = $bt[0];
		$file = basename( $bt['file']);
		$log = sprintf( "<H3 class=debugger>%15s:%4s (%10s) </H3>\n", $file, $bt['line'], $bt['function'] );
		$log .= str_replace("'", '"', $message );
		
		$lines = split("\n", $log);
		?>
		
	    <script type="text/javascript">
	    <?php foreach( $lines as $line )
	    {?>
			myvar += '<?php print $line ?>\n';
		<?php 
		}?>
		$("#debuglog").text(myvar);
		</script>
	    <?php 
	    
	}
	
	function __destruct()
	{
	?>
		<script type="text/javascript">
	    $("#debuglog").html( myvar )
	    </script>
	<?php 	
	}

}
?>