How to Log to Console in PHP

Kim Sia Developer Tips, Tricks & Resources

PHP is one of the most popular server-side scripting languages for building web applications because it’s easy to use. No matter what you build, making it easy to log errors is key to ensuring a short code-test-learn feedback cycle. Because PHP was developed way before today’s modern browsers, it didn’t really have an easy way to log errors to the browser console—even though the browser is the main way to interact with websites and web applications and PHP is uniquely designed to be good for building web applications. Using JavaScript, logging to console is as simple as this:

console.log("Message here");

In this article, I will show you how to log to console within PHP, why logging in PHP can be a good thing, and how it’s just as easy as logging to console using JavaScript. So you can have the best of both worlds: enjoy the power and ease of a great web programming language like PHP andstill log to console within PHP.

What is the browser console?

First of all, we need to understand what the browser console is.

The browser console is a way for the browser to log information associated with a specific web page. The information logged includes network requests, JavaScript, CSS, security errors, and warnings as well as error, warning, and informational messages explicitly logged by JavaScript code running in the page context.

For the rest of this article, I’ll be using desktop Google Chrome for demonstration. You can actually perform similar steps in modern browsers like the desktop versions of Firefox, Safari, and Internet Explorer. When you open Google Chrome and go to any web page, right-click, and choose Inspect, you’ll bring up Chrome’s Developer Tools.

Fig. 1: How to trigger Developer Tools in Chrome

Fig. 2: Developer Tools in Chrome after clicking on Inspect

The browser console will be one of the tabs in the Developer Tools. And you can test it out by writing the same JavaScript console.log command.

Fig. 3: How to log to console using JavaScript


PHP Retrace

Why logging to console is a good thing

There are two primary reasons you want to log to the browser console.

The first is simplicity. As a PHP developer, you want to work with, at most, two applications: your favorite code editor or IDE and your browser. You toggle between the two as you write code in the editor and test it on the browser. The most natural place to display log statements is inside the browser.

The second reason is to keep the logging as least intrusive as possible. Now, you can log using PHP’s native functions such as var_dump. However, when you use var_dump, you need to decide where you want to write the output to. It could be the browser web page, but this will likely distort the display. Another possible destination for output may be a file in your server, for which I’d recommend an open-source logging library like monolog instead of var_dump. If you prefer to output view variables (e.g., variables that are more related to display) and don’t want to distort the web page, logging to the browser console might be a better idea.

Another thing to note is that, increasingly, PHP developers gravitate toward frameworks such as Laravel and Symfony, which usually use popular PHP logging libraries such as monolog. These libraries work best when you want a detailed breakdown of the error stack trace for server-side errors such as database connection and outputting these into files. By the way, Stackify’s tutorials also cover monolog logging for such situations, where you can learn how to send the logs to Retrace.

Sometimes you just want something lightweight to display inside the browser for front-end debugging. For such situations, logging to console would be ideal. Furthermore, you can combine this technique with the standard PHP logging methods for a more complete development setup.

How to log directly to console using PHP code

There are two main ways you can log directly to the console using (mostly) PHP code. I can summarize it as using json_encode function and using PHP libraries.

Using json_encode function

Let’s say you want to console log a PHP variable $view_variable in your view layer. Recall that console.log is a JavaScript function. The key principle is that we can make use of JSON to pass the PHP variable to the JavaScript function. You create a PHP function like this:

<?php
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}

You can call this function at exactly the place you want to run the console_log that we just created, as seen above. An example of its usage would look like this:

<?php $view_variable = 'a string here'; ?>
<!-- some HTML content here -->
<div>
<!-- even more HTML content here -->
</div>
<?= console_log($view_variable); ?>

And the generated HTML markup would be this:

<!-- some HTML content here -->
<div>
<!-- even more HTML content here -->
</div>
<script>console_log('a string');</script>

As long as you remember to include the definition of the customized console_log PHP function, you can call it as many times as you need to. If you prefer to transform the JSON string into other forms, you can reference the list of constants that json_encode uses. The useful constants that you’re more likely to use are JSON_FORCE_OBJECT and JSON_PRETTY_PRINT.

Logging in the middle of your JavaScript code

Sometimes, you don’t want to install PHP libraries only when you’re absolutely sure you have to. So, you might prefer to console log the PHP variables in the middle of your JavaScript code found in your PHP view files. You can make use of the same technique this way:

<script>
// other JavaScript code before ...

var js_variable_as_placeholder = <?= json_encode($view_variable,
JSON_HEX_TAG); ?>;
console.log(js_variable_as_placeholder);

// other JavaScript code and after ...
</script>

Using PHP libraries to console log

If you prefer to use open-source libraries that have solved this issue, there are two candidates I recommend. They are PHPDebugConsole (installation instructions and code here) and PHPConsole (installation instructions and code here).

A comparison between PHPDebugConsole and PHPConsole

A quick comparison between the two libraries yields the following analysis.

PHPConsole appears to be more established with 1,191 stars on its GitHub repo, while PHPDebugConsole has fewer than 30 stars. At the time of writing, PHPConsole hasn’t been updated since late 2018 and has fewer commits (128) compared with PHPDebugConsole at 256 commits. PHPDebugConsole has a more frequent update history with the last three commits all happening in January 2019. PHPDebugConsole also has better documentation. Their documentation explicitly recommends several browser extensions that it can work with and includes demo examples. PHPConsole, on the other hand, recommends a Chrome Extension that seems to be authored by the same people behind PHPConsole. However, their demo website is not working as of the time I’m writing this.

Taking all the above into consideration, I have to recommend choosing PHPDebugConsole if you want to use a PHP library to console log. Overall, I’d recommend the following decision matrix:

  • If you want to keep it simple, use PHP json_encode function.
  • If you want to use more extensive features such as console.info, use PHPDebugConsole with PHPConsole as your backup option.
An example from PHPDebugConsole

Here’s an example taken from PHPDebugConsole’s excellent demo website:

<?php
require '/path/to/Debug.php';

$debug = new \bdk\Debug(array(
'collect' => true, // turn logging on
'output' => true, // if left false (default), the output() method will return an empty string
));

/**
* Example Class
* Demonstrates PHP reflection and PHPDocBlock
*/
class Example
{
private $offLimits = 'I\'m a private property';

public function __toString() {
return 'It\'s Magic';
}

/**
* Foo is a private method that does stuff
*
* @param string $bar the string you want to foo
*
* @return string the fooed string
*/
private function foo($bar) {
}
}

$debug->info('PHPDebugConsole is great!');
$debug->warn('No browser plugin necessary');
$debug->log('features/options', array(
'PHP port of the javascript web console API',
'outputOpts' => array(
'HTML (as seen here)',
'ChromeLogger',
'FirePHP',
'Plain-text / file',
'<script>',
'"plugin" (send log realtime via websockets, etc)',
),
'password protected',
'errors (even fatal) are captured / logged / displayed',
'send error notices via email (throttled as to not to send out a flood of emails)',
'send debug log via email',
));

When this runs, it looks like this within the web page content. If you do want it to be output to the browser’s console, you need to install extensions.

Fig. 4: Example output for PHPDebugConsole

Conclusion

We live in a highly interesting and exciting time for web programming. The console log used to be something that could only work with JavaScript. In this article, you’ve learned what the console log is, why it’s useful for web development, and how you can write your own PHP code to log PHP variables in your browser console. If you need more extensive features such as console.info, there are PHP libraries like PHPDebugConsole that can help you with that.

To make it a complete, end-to-end logging infrastructure for your PHP web application, I highly recommend using monolog as well to cover more back-end-related debugging purposes. Tie it all together by using an application performance monitoring tool such as Retrace to track your application performance, search through all your logs easily, and identify top web requests and their impact on your stack. Do that, and I guarantee you’ll have a solid logging setup that’s better than the majority of PHP web applications out there.

About Kim Sia

This post was written by KimSia. KimSia writes under the nom de plume T.J. Simmons. He started his own developer firm five years ago, building solutions for professionals in telecoms and the finance industry who were overwhelmed by too many Excel spreadsheets. He’s now proficient with the automation of document generation and data extraction from varied sources.