As a programming language, PHP is a developer favorite. An essential PHP programming best practice is how to log to console in PHP. Today, we’ll lay out how you do that.
PHP is one of the most popular server-side scripting languages for building web applications because it’s easy to use. But no matter what you build, logging errors is key to ensuring a short code-test-learn feedback cycle.
PHP has a unique design that makes it suitable for building web applications. However, developers created PHP before the advent of modern browsers. So it doesn’t provide an easy method to log errors to the browser console. Using JavaScript, logging to console is as simple as this:
console.log("Message here");
In this post, we will guide you on logging to the console in PHP. We will also explain why logging within PHP can benefit you. Furthermore, we’ll tackle how it’s just as easy as logging to console using JavaScript. You can have the best of both worlds: enjoy the power of PHP and log to console within PHP.
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 system logs several types of information in the page context. This includes network requests, JavaScript details, CSS data and security errors and warnings. Additionally, the system logs errors, warnings and informational messages that JavaScript code on the page explicitly generates.
For demonstrations, we’ll use the desktop version of Google Chrome.
Note: You can also perform similar steps in desktop versions of Firefox, Safari and Internet Explorer.
To start, open Google Chrome and go to any web page. Then right-click and choose Inspect to bring up Chrome’s Developer Tools.
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.
There are two primary reasons you want to log to the browser console.
The first is simplicity. As a PHP developer, you typically use two applications: your preferred code editor or IDE and your browser. You often switch between these two as you write code in the editor and test it in the browser. Therefore, displaying log statements inside the browser is convenient and sensible.
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.
You could write output to the browser web page, but this will likely distort the display. Another possible destination for output may be a file in your server. For this option, we recommend an open-source logging library like Monolog instead of var_dump. If you prefer to output view variables without distorting the web page, logging to the browser console is better
Another thing to note is that PHP developers are increasingly gravitating toward frameworks such as Laravel and Symfony. These frameworks usually use popular PHP logging libraries such as Monolog.
PHP logging libraries work best when they analyze the error stack trace in detail. This analysis holds particular significance for server-side errors, including complications associated with database connection issues. The libraries record these details into files.
We have a tutorial covering Monolog logging for such situations. With this tutorial 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.
There are two main ways you can log directly to the console using:
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 the exact place you want to run the console_log that we just created above. An example of its usage would look 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 the exact place you want to run the console_log that we just created 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>
Remember to include the definition of the customized console_log PHP function to call it as many times as needed. If you want to change the JSON string into different formats, you can use the list of constants. The most popular constants are JSON_FORCE_OBJECT and JSON_PRETTY_PRINT.
You may want to avoid installing PHP libraries unless necessary. Instead, you can log the PHP variables directly within your JavaScript code in the PHP view files, using the same technique.
<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>
If you prefer to use open-source libraries that have solved this issue, there are two options we recommend
A quick comparison between the two libraries yields the following analysis.
As of 2023, PHPConsole appears to be more established with 1.4k stars on its GitHub repo. At the time of writing, PHPConsole’s last update was September 2019 and has fewer commits (126). The same people behind PHPConsole seem to author a Chrome Extension for PHPConsole, and it is advisable to use it. Finally, the PHPConsole demo website was no longer working, when I checked last.
As of 2023, PHPDebugConsole has 72 stars on GitHub, with a frequent update history. It has 1040 commits. Documentation recommends several browser extensions that PHPDebugConsole can work with and includes demo examples.
Taking all the above into consideration, we recommend choosing PHPDebugConsole if you want to use a PHP library to console log. Overall, we suggest the following decision matrix:
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 the web page content below. If you do want it to be output to the browser’s console, you need to install extensions.
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 post, you’ve learned what the console log is and why it’s useful for web development.
You’ve also learned how to 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.
For a comprehensive logging system in your PHP web application, consider using Monolog for back-end debugging. Integrate Monolog with a performance monitoring tool like Retrace. This will help to track application performance, search logs and identify key web requests and their effects. The combination will provide a robust logging setup superior to most PHP web applications.
You may also want to try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix now provides OpenTelementry data ingestion, which works with .NET, Java, PHP, Node.js, Ruby, Python, C++, Erlang/Elixer, Go, Rust and Swift.
If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]