on Tips

Debugging PHP in browser’s Javascript console

13 comments
firebug
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

Debugging PHP is often done in many ways. By printing some info on the screen, using die or var_dump, using log files in which you can always write errors, warnings and similar. The bad thing is, it will destroy your layout, and it will be barely readable.

But why not using only one tool for all scripts (PHP and Javascript). As FireFox and Chrome have Javascript consoles, we can easily use them to debug PHP, too. This way you can have nice colored output, with line numbers and everything you need. The best thing is you can print arrays or even the whole object to console.

You will say that it will destroy browsers that do not use/have console, like IE. But I have taken care of that, too.

First, I will show you the class that is responsible for the whole thing:

class PHPDebug {
    
function __construct() {
    if (!defined("LOG"))    define("LOG",1);
    if (!defined("INFO"))   define("INFO",2);
    if (!defined("WARN"))   define("WARN",3);
    if (!defined("ERROR"))  define("ERROR",4);

    define("NL","\r\n");
    echo '<script type="text/javascript">'.NL;
    
    /// this is for IE and other browsers w/o console
    echo 'if (!window.console) console = {};';
    echo 'console.log = console.log || function(){};';
    echo 'console.warn = console.warn || function(){};';
    echo 'console.error = console.error || function(){};';
    echo 'console.info = console.info || function(){};';
    echo 'console.debug = console.debug || function(){};';
    echo '</script>';
    /// end of IE    
}

function debug($name, $var = null, $type = LOG) {
    echo '<script type="text/javascript">'.NL;
    switch($type) {
        case LOG:
            echo 'console.log("'.$name.'");'.NL;    
        break;
        case INFO:
            echo 'console.info("'.$name.'");'.NL;    
        break;
        case WARN:
            echo 'console.warn("'.$name.'");'.NL;    
        break;
        case ERROR:
            echo 'console.error("'.$name.'");'.NL;    
        break;
    }
    
    if (!empty($var)) {
        if (is_object($var) || is_array($var)) {
            $object = json_encode($var);
            echo 'var object'.preg_replace('~[^A-Z|0-9]~i',"_",$name).' = \''.str_replace("'","\'",$object).'\';'.NL;
            echo 'var val'.preg_replace('~[^A-Z|0-9]~i',"_",$name).' = eval("(" + object'.preg_replace('~[^A-Z|0-9]~i',"_",$name).' + ")" );'.NL;
            switch($type) {
                case LOG:
                    echo 'console.debug(val'.preg_replace('~[^A-Z|0-9]~i',"_",$name).');'.NL;    
                break;
                case INFO:
                    echo 'console.info(val'.preg_replace('~[^A-Z|0-9]~i',"_",$name).');'.NL;
                break;
                case WARN:
                    echo 'console.warn(val'.preg_replace('~[^A-Z|0-9]~i',"_",$name).');'.NL;        
                break;
                case ERROR:
                    echo 'console.error(val'.preg_replace('~[^A-Z|0-9]~i',"_",$name).');'.NL;    
                break;
            }
        } else {
            switch($type) {
                case LOG:
                    echo 'console.debug("'.str_replace('"','\\"',$var).'");'.NL;
                break;
                case INFO:
                    echo 'console.info("'.str_replace('"','\\"',$var).'");'.NL;
                break;
                case WARN:
                    echo 'console.warn("'.str_replace('"','\\"',$var).'");'.NL;    
                break;
                case ERROR:
                    echo 'console.error("'.str_replace('"','\\"',$var).'");'.NL;
                break;
            }
        }
    }
    echo '</script>'.NL;
}
}

I will not go into details about the code, as it should be understandable to medium experienced PHP programmer. Basically, this class is generating JavaScript to insert messages or variables to console. Simple as that.

The part that is dealing with IE is creating empty functions for every console function we are using, and thus IE is working despite of writing to console. Cool.

Now, how to use this class, below is code that is used on the DEMO page:

// include and instantiate the class
    require_once("PHPDebug.php");
    $debug = new PHPDebug();
    
    // simple message to console
    $debug->debug("A very simple message");
    
    // vaiable to console
    $x = 3;
    $y = 5;
    $z = $x/$y;
    $debug->debug("Variable Z: ", $z);
    
    // a warnign
    $debug->debug("A simple Warning", null, WARN);
    
    // info
    $debug->debug("A simple Info message", null, INFO);
    
    // An error
    $debug->debug("A simple error messsage", null, ERROR);
    
    // Array in console
    $fruits = array("banana", "apple", "strawberry", "pineaple");
    $fruits = array_reverse($fruits);
    $debug->debug("Fruits array", $fruits);
    
    
    // object to console
    $book               = new stdClass;
    $book->title        = "Harry Potter and the Prisoner of Azkaban";
    $book->author       = "J. K. Rowling";
    $book->publisher    = "Arthur A. Levine Books";
    $book->amazon_link  = "http://www.amazon.com/dp/0439136369/";
    $debug->debug("Object", $book);

To see above code in action, open your console (in FireFox or Google Chrome) and go to the DEMO PAGE.

You can do the same with Internet Explorer, and the div containing message will appear, and IE will not break.

Above code is free and you can use it however you see fit.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Pingback: Tweets that mention Debugging PHP in browser’s Javascript console | CodeForest -- Topsy.com

  • Bibi Sayman

    Thanks for sharing your script, I had a problem getting it installed but it was all my inability to get things in the right place;)

  • Bruno Inzana

    I always learn something new

  • http://www.zimbio.com/Bestsiouxfallswebdesign/articles/1l3Z6c2Y1b4/Major+10+Suggestions+Sioux+Falls+Webdesigners Sanford Ebbs

    amazing stuff thanx Such a usefule blog…wow !!!!

  • http://www.onlineouijaboard.net Online Ouija Board

    i was just thinking this same thing prior lol, fantastic post

  • Noma Bolvin

    I agree with your post absolutely and I am now interested in reading some more of your posts on your blog and see what you have to say. Do you mind if I tweet your blog post out to my followers on twitter? I think they would also enjoy the blog post. Thanks.

    • Zvonko

      Of course you can tweet my post.

  • http://carlosvidal.pe Carlos Vidal

    Hi Zvonko

    I’m not a PHP expert, so I need some help. I have tried to use your class as a Codeigniter library, but I’m getting the fallowing error.

    A PHP Error was encountered
    Severity: Notice
    Message: Constant NL already defined
    Filename: libraries/Phpdebug.php
    Line Number: 10

    I have search all over the Codeigneter framework and NL not defined there.

    Any clues?

  • Pingback: Debugging PHP in a floating javascript window | Cozy Coding

  • http://cozycoding.wordpress.com Cozy Coding

    Hi Zvonko,

    Cool post. This gave me the idea to do something similar where I display to a javascript window rather than to the console. Check out my blog at http://cozycoding.wordpress.com/2011/04/03/debugging-php-in-a-floating-javascript-window/

  • Jimmy

    There is also great Google Chrome extension – PHP Console https://chrome.google.com/webstore/detail/nfhmhhlpfleoednkpnnnkolmclajemef

  • http://popnoodles.com Nigel

    This is a great script but for one change – strings with multiple lines break JS.

    echo ‘console.log(‘.json_encode($name).’);’.NL;

    fixes it

  • Pingback: Informazioni di debug PHP in console Javascript « Pcs86's Weblog