This snippet allows you to log things to your browser console. This snippet incorporates the underlying aspects of the native javascript function, but makes it easy to use in your PHP scripts and makes it easy for PHP developers. I usually put this script in a helper.php file and include it in my index.php file, which routes every other page.

Then, all you need to do is console_log($dataYouWantToSendToTheConsole);

/**
 * Send data via PHP to your Browser's Console
 *
 * @param $data
 */
function console_log($data) {
    $consoleOutput = '<script>' . 'console.log(' . json_encode($data, JSON_HEX_TAG) .');'. '</script>';
    echo $consoleOutput;
}

This code snippet was published on It was last edited on

Contributing Authors

1

1 Comment

  • Votes
  • Oldest
  • Latest
Commented
Updated

The snippet above is good in the sense you do not need any 3rd party tools to make it work. However, there are a few useful tools that you can utilize to make things easier:

Firefox

You can use the FirePHP Firefox plugin to enable logging and information dumps from your PHP apps to the console. This is an addition to the fantastic Firebug web development extension.

FirePHP function to initiate browser logging

FirePHP browser console messages

Chrome

Chrome Logger often known as webug, is a PHP debugging tool that you can use if you're using Chrome (webug has problems with the order of logs).

Webug console variant off of Firebug

Clockwork, which is currently in active development, adds a new panel to the Developer Tools to provide essential debugging and profiling information. It comes with out-of-the-box support for Slim and Laravel, and its extendable API allows for the addition of support.

Utilizing Xdebug

While this actually does not send data to your browser console, using Xdebug to debug your PHP might be preferable. The majority of browsers offer assistance extensions to make it easier for you to pass the necessary cookie/query string to start the debugging process. Then you can see the data in real-time with your IDE as you step the programming logic.

See Xdebug Helper for Chrome, Xdebug Session Cookie for Firefox, and Xdebug Toggler for Safari.

add a comment
0