Tutorial: Log to Console in PHP
Logging is a key aspect of monitoring, troubleshooting and debugging your code.
Not only does it make your project’s underlying execution more transparent and intelligible, but also more accessible in its approach. In a company or a community setting, intelligent logging practices can help everyone to be on the same page about the status and the progress of the project.
In this post, we’ll see how we can refine our PHP web development practices by understanding the importance of logging to the browser console. We’ll see how logging is natively supported in PHP, and how doing it in the browser console has more to offer than printing logs on webpages or writing logs to files.
Use these links to navigate:
Background — Logging in PHP
More than 25 years since its creation, PHP is still one of the most widely used programming languages in the world, accounting for about 78% of the known internet.
Though when I started programming in PHP, I realized that my background in Javascript had not prepared me for this. I was so used to working with the browser’s console for debugging, that having to work with PHP’s native logging support couldn’t fill that void. But there was hope!
Before that, let’s see how PHP natively supports logging and debugging.
PHP can be used for logging through two primary ways —
- By either writing to log files on the disk or
- By displaying variable values on web-pages using echo and var_dump .
Both these options can prove to be restrictive.
Though static log files help in a retrospective analysis of how the execution unfolded, they can in some sense deprive you of the rich real-time experience of monitoring the dynamics of a modern website bustling with network requests and socket connections.
Also, there is only so much information that you can log onto your web-page without disrupting it’s design. Conventional logging mechanisms possible in PHP can, therefore, seem less viable for more extensive, dynamic websites.
The aforementioned issues restrict logging capabilities not only for PHP but for any language that was going to be used for web development in the future.
Modern browsers came to the rescue and realized the importance of providing developers with the necessary tools to make way for some easy, yet powerful logging and debugging support. These are also known as the Developer Tools and can be accessed by right-clicking on the web-page and selecting the ‘Inspect’ option.
These tools allow you to inspect the DOM object, monitor network requests and responses, page load times, website performance, memory consumption and so much more.
One of these Developer Tools, known as the browser’s console allows you to log messages and run Javascript code to debug your application. Let’s see how we can use that to our advantage.
The Basics of Browser Console Logging
When something goes wrong on a website, usually the user is shown a fancy error message about what happened.
But a web developer’s window to what might have gone wrong is the browser’s Dev Tools — primarily the browser console.
What is a browser console?
The browser console, as the name suggests, is a console in the browser.
Just as you can run Python or Node.js code on a console in your terminal, and print results and log errors, the console in your browser allows you to run Javascript code and log information pertinent to your website.
Let us understand this through an example. Let’s say you created an online messaging platform and due to some unknown reason, users on your website weren’t able to receive messages from their friends. Now in such a case, it would be handy to have a clear-cut logging system in place that could help you put a finger on what went wrong and where. The following is an example of a log:
- Database connected
- Fetching user’s friends
- Processing data
- Rendering data
- Opening socket connection
- Successful socket connection
- Sending a message on channel
- Received a message on channel
- Rendering message
- [ERROR IN RENDERING MESSAGE]
As shown in the above example, well-implemented logs would help you figure out that even though the message content was received, it was in rendering it that your code failed. Now you can go ahead and directly jump to the relevant portion of your code and make the necessary changes.
You can print information to the console by using the console.log() method.
Depending on the requirement, other methods of the console object can also be used —
- console.info()
- console.debug()
- console.warn()
- console.error()
Where is it?
In Google Chrome, you can access the browser console by either using Cmd + Shift + C (Ctrl + Shift + C on Windows, Linux) or by navigating to the ‘Console’ tab in the Dev Tools after selecting the ‘Inspect’ menu option.
How Console Logging Can be Done in PHP
Despite PHP’s supremacy, the fact that all modern browsers chose Javascript as the browser interpreter language meant that the only way PHP code logs could make it to the browser’s console was going to be through custom helper functions. These functions can call Javascript’s console.log() by echo ing it to the required webpage.
This is the basis of how one can utilize the capabilities of a JS-based browser console for a PHP-based environment.
Let’s look at how we can make use of the above to log more often and more flexibly:
- Using json_encode()
The above example was just to print hard-coded message strings that informed about the status and progress of a certain subtask.
It is also very common to debug by logging data variables, such as to request parameters, JSON (Javascript Object Notation) responses, processed outputs, etc. Let us see how we can print a PHP array to the browser console.
CONSOLE OUTPUT:
The json_encode() function converts the PHP variable into a JSON object that can be parsed by Javascript for printing to the console. Our pretty PHP file is converted by the browser to the following HTML markup —
(inspected from the ‘Sources’ section of the Developer Tools)
The json_encode() function can be used for converting any PHP data type to a Javascript compatible notation.
Instead of writing the corresponding echo statement each time we want to log something to the console, we can make a function for the same as such —
The above function can be used however we like depending on if we want the enclosing <script> tags to be added automatically or not.
CONSOLE OUTPUT:
Using PHP libraries to console log
If you want to outsource this logging middleware code to a helper Open Source library that allows more functionality, then you can look at something like PHPConsole or PHPDebugConsole .
PHPConsole is more popular on Github but is a little old, and less frequently updated. It works with a browser extension (for Chrome) to log information to the browser console. Code and installation instructions can be found here .
On the other hand, PHPDebugConsole, though it has only 34 stars on Github, is more frequently maintained and has better documentation. Code, installation information and usage instructions of the library can be found here .
By default, it outputs logs on the web-page in an organized fashion. Here is a usage example provided on their website that shows how easy it is to get started with logging using PHPDebugConsole.
Below is an example of HTML output from their website.
They also provide support for logging to the browser’s console by installing certain extensions.
If you are working on a small scale personal project, in my opinion, nothing would match the simplicity of using your custom json_encode() based helper function. It would save you from taking care of the external dependencies and browser cross-compatibility.
Why You Should be Logging to Console
Convenience
Logging to the browser console certainly has a convenience factor. It is easier for a developer to have the errors logged right next to the web-page’s display. This way the developer only has to switch between the IDE and the browser as compared to having a log file open on the side that is more likely to not be auto-refreshing.
Real-time monitoring of results
Since a major portion of a website’s functioning is the web-page’s display and content rendering, it is important for the developer to be able to monitor the logs and the web site’s performance in real-time as the web-page unfolds and as the user interacts with the website. This synchrony can make way for new insights about how the website is performing and about relevant improvements that can be made.
Saves you from going through hefty static log files
Even though in many cases it is important to track and maintain log files for large-scale projects to analyze and assess performance, it can be slightly disappointing to realize that in PHP it is the only logging support that the language provides. For less important debugging logs, it can be nice to have a console that displays results as and when required.
Doesn’t mess with webpage
PHP’s echo and var_dump can be sometimes used to log and monitor data on the web page. But like we discussed before it disrupts your web page’s display, affects user experience and is not a good practice for extensive projects. Below is an example —
The fact that a separate browser console window can be used for displaying the logs means that developers don’t need to worry about distorting the web-page layout or about the formatting of their logs.
print_r
print_r() displays information about a variable in a way that's readable by humans.
print_r() , var_dump() and var_export() will also show protected and private properties of objects. Static class members will not be shown.
Parameters
The expression to be printed.
If you would like to capture the output of print_r() , use the return parameter. When this parameter is set to true , print_r() will return the information rather than print it.
Return Values
If given a string , int or float , the value itself will be printed. If given an array , values will be presented in a format that shows keys and elements. Similar notation is used for object s.
When the return parameter is true , this function will return a string . Otherwise, the return value is true .
Examples
Example #1 print_r() example
The above example will output:
Example #2 return parameter example
Notes
Note:
When the return parameter is used, this function uses internal output buffering prior to PHP 7.1.0, so it cannot be used inside an ob_start() callback function.
See Also
- ob_start() — Turn on output buffering
- var_dump() — Dumps information about a variable
- var_export() — Outputs or returns a parsable string representation of a variable
User Contributed Notes 36 notes
I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.
<?php
function print_r2 ( $val ) <
echo ‘<pre>’ ;
print_r ( $val );
echo ‘</pre>’ ;
>
?>
It also makes sense in some cases to add an if statement to only display the output in certain scenarios, such as:
I’ve fixed function wrote by Matt to reverse print_r — it had problems with null values. Created a GIST for that too so please add any future fixes in there instead of this comment section:
https://gist.github.com/simivar/037b13a9bbd53ae5a092d8f6d9828bc3
<?php
/**
* Matt: core
* Trixor: object handling
* lech: Windows suppport
* simivar: null support
*
* @see http://php.net/manual/en/function.print-r.php
**/
function print_r_reverse ( $input ) <
$lines = preg_split ( ‘#\r?\n#’ , trim ( $input ));
if ( trim ( $lines [ 0 ]) != ‘Array’ && trim ( $lines [ 0 ] != ‘stdClass Object’ )) <
// bottomed out to something that isn’t an array or object
if ( $input === » ) <
return null ;
>
return $input ;
> else <
// this is an array or object, lets parse it
$match = array();
if ( preg_match ( «/(\s<5,>)\(/» , $lines [ 1 ], $match )) <
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match [ 1 ];
$spaces_length = strlen ( $spaces );
$lines_total = count ( $lines );
for ( $i = 0 ; $i < $lines_total ; $i ++) <
if ( substr ( $lines [ $i ], 0 , $spaces_length ) == $spaces ) <
$lines [ $i ] = substr ( $lines [ $i ], $spaces_length );
>
>
>
$is_object = trim ( $lines [ 0 ]) == ‘stdClass Object’ ;
array_shift ( $lines ); // Array
array_shift ( $lines ); // (
array_pop ( $lines ); // )
$input = implode ( «\n» , $lines );
$matches = array();
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all ( «/^\s<4>\[(.+?)\] \=\> /m» , $input , $matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
$pos = array();
$previous_key = » ;
$in_length = strlen ( $input );
// store the following in $pos:
// array with key = key of the parsed array’s item
// value = array(start position in $in, $end position in $in)
foreach ( $matches as $match ) <
$key = $match [ 1 ][ 0 ];
$start = $match [ 0 ][ 1 ] + strlen ( $match [ 0 ][ 0 ]);
$pos [ $key ] = array( $start , $in_length );
if ( $previous_key != » ) <
$pos [ $previous_key ][ 1 ] = $match [ 0 ][ 1 ] — 1 ;
>
$previous_key = $key ;
>
$ret = array();
foreach ( $pos as $key => $where ) <
// recursively see if the parsed out value is an array too
$ret [ $key ] = print_r_reverse ( substr ( $input , $where [ 0 ], $where [ 1 ] — $where [ 0 ]));
>
return $is_object ? (object) $ret : $ret ;
>
>
?>
Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.
<?php
function print_r_reverse ( $in ) <
$lines = explode ( «\n» , trim ( $in ));
if ( trim ( $lines [ 0 ]) != ‘Array’ ) <
// bottomed out to something that isn’t an array
return $in ;
> else <
// this is an array, lets parse it
if ( preg_match ( «/(\s<5,>)\(/» , $lines [ 1 ], $match )) <
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match [ 1 ];
$spaces_length = strlen ( $spaces );
$lines_total = count ( $lines );
for ( $i = 0 ; $i < $lines_total ; $i ++) <
if ( substr ( $lines [ $i ], 0 , $spaces_length ) == $spaces ) <
$lines [ $i ] = substr ( $lines [ $i ], $spaces_length );
>
>
>
array_shift ( $lines ); // Array
array_shift ( $lines ); // (
array_pop ( $lines ); // )
$in = implode ( «\n» , $lines );
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all ( «/^\s<4>\[(.+?)\] \=\> /m» , $in , $matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
$pos = array();
$previous_key = » ;
$in_length = strlen ( $in );
// store the following in $pos:
// array with key = key of the parsed array’s item
// value = array(start position in $in, $end position in $in)
foreach ( $matches as $match ) <
$key = $match [ 1 ][ 0 ];
$start = $match [ 0 ][ 1 ] + strlen ( $match [ 0 ][ 0 ]);
$pos [ $key ] = array( $start , $in_length );
if ( $previous_key != » ) $pos [ $previous_key ][ 1 ] = $match [ 0 ][ 1 ] — 1 ;
$previous_key = $key ;
>
$ret = array();
foreach ( $pos as $key => $where ) <
// recursively see if the parsed out value is an array too
$ret [ $key ] = print_r_reverse ( substr ( $in , $where [ 0 ], $where [ 1 ] — $where [ 0 ]));
>
return $ret ;
>
>
This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky. ):
<?php
/**
* An alternative to print_r that unlike the original does not use output buffering with
* the return parameter set to true. Thus, Fatal errors that would be the result of print_r
* in return-mode within ob handlers can be avoided.
*
* Comes with an extra parameter to be able to generate html code. If you need a
* human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
*
* Support for printing of objects as well as the $return parameter functionality
* added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
* replacement for print_r (Except for that this function does not output
* paranthesises around element groups. 😉 )
*
* Based on return_array() By Matthew Ruivo (mruivo at gmail)
* (http://se2.php.net/manual/en/function.print-r.php#73436)
*/
function obsafe_print_r ( $var , $return = false , $html = false , $level = 0 ) <
$spaces = «» ;
$space = $html ? « » : » » ;
$newline = $html ? «<br />» : «\n» ;
for ( $i = 1 ; $i <= 6 ; $i ++) <
$spaces .= $space ;
>
$tabs = $spaces ;
for ( $i = 1 ; $i <= $level ; $i ++) <
$tabs .= $spaces ;
>
if ( is_array ( $var )) <
$title = «Array» ;
> elseif ( is_object ( $var )) <
$title = get_class ( $var ). » Object» ;
>
$output = $title . $newline . $newline ;
foreach( $var as $key => $value ) <
if ( is_array ( $value ) || is_object ( $value )) <
$level ++;
$value = obsafe_print_r ( $value , true , $html , $level );
$level —;
>
$output .= $tabs . «[» . $key . «] => » . $value . $newline ;
>
if ( $return ) return $output ;
else echo $output ;
>
?>
Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)
print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!
<?php
print_neat_classes_r ( $array , $return = false ) <
return print_r ( self :: neat_class_print_r ( $array ), $return );
>
function do_print_r ( $array , $return = false ) <
if( is_object ( $array ) && method_exists ( $array , ‘toArray’ )) <
return $array -> toArray ();
>else if( is_array ( $array )) <
foreach( $array as $key => $obj ) <
$array [ $key ] = self :: do_print_r ( $obj , $return );
>
return $array ;
>else <
return $array ;
>
>
?>
I always use this function in my code, because most of my functions return an Array or Boolean :
function printr ( $object , $name = » ) <
if ( is_array ( $object ) ) <
print ( ‘<pre>’ ) ;
print_r ( $object ) ;
print ( ‘</pre>’ ) ;
> else <
var_dump ( $object ) ;
>
?>
( print_r gives no output on FALSE and that can be annoying! )
print_r(), just like var_dump() does NOT cast an object, not even if it has a __toString() method — which is normal.
<?php
class A <
public function __toString () <
return ‘In class A’ ;
>
>
$a = new A ;
echo $a ; // In class A
print_r ( $a ); // A Object()
// you can simulate the echo by casting it manually
print_r ((string) $a ); // In class A
Here is a function that formats the output of print_r as a expandable/collapsable tree list using HTML and JavaScript.
<?php
function print_r_tree ( $data )
<
// capture the output of print_r
$out = print_r ( $data , true );
// replace something like ‘[element] => <newline> (‘ with <a href=»javascript:toggleDisplay(‘. ‘);»>. </a><div style=»display: none;»>
$out = preg_replace ( ‘/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe’ , «‘\\1<a href=\»javascript:toggleDisplay(\».(\$id = substr(md5(rand().’\\0′), 0, 7)).’\’);\»>\\2</a><div style=\»display: none;\»>'» , $out );
// replace ‘)’ on its own on a new line (surrounded by whitespace is ok) with ‘</div>
$out = preg_replace ( ‘/^\s*\)\s*$/m’ , ‘</div>’ , $out );
// print the javascript function toggleDisplay() and then the transformed output
echo ‘<script language=»Javascript»>function toggleDisplay(id) < document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; ></script>’ . «\n $out » ;
>
?>
Pass it a multidimensional array or object and each sub-array/object will be hidden and replaced by a html link that will toggle its display on and off.
Its quick and dirty, but great for debugging the contents of large arrays and objects.
Note: You’ll want to surround the output with <pre></pre>
The following will output an array in a PHP parsable format:
<?php
function serialize_array (& $array , $root = ‘$root’ , $depth = 0 )
<
$items = array();
foreach( $array as $key => & $value )
<
if( is_array ( $value ))
<
serialize_array ( $value , $root . ‘[\» . $key . ‘\’]’ , $depth + 1 );
>
else
<
$items [ $key ] = $value ;
>
>
if( count ( $items ) > 0 )
<
echo $root . ‘ = array(‘ ;
$prefix = » ;
foreach( $items as $key => & $value )
<
echo $prefix . ‘\» . $key . ‘\’ => \» . addslashes ( $value ) . ‘\» ;
$prefix = ‘, ‘ ;
>
liamtoh6@hotmail.com posted a function that will echo print_r output with proper new lines in HTML files. He used <pre> for it to work, but that might not be always the best method to go. For example, it is not valid to place <pre> inside <p>.
Here is my way to do this:
function print_rbr ( $var , $return = false ) <
$r = nl2br ( htmlspecialchars ( print_r ( $var , true )));
if ( $return ) return $r ;
else echo $r ;
>
— Place <br> where newlines are,
— Escape unsecure characters with HTML entities.
Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)
<?php
header ( ‘Content-Type: text/xml; charset=UTF-8’ );
echo print_r_xml ( $some_var );
function print_r_xml ( $arr , $first = true ) <
$output = «» ;
if ( $first ) $output .= «<?xml version=\»1.0\» encoding=\»UTF-8\»?>\n<data>\n» ;
foreach( $arr as $key => $val ) <
if ( is_numeric ( $key )) $key = «arr_» . $key ; // <0 is not allowed
switch ( gettype ( $val )) <
case «array» :
$output .= «<» . htmlspecialchars ( $key ). » type=’array’ size='» . count ( $val ). «‘>» .
print_r_xml ( $val , false ). «</» . htmlspecialchars ( $key ). «>\n» ; break;
case «boolean» :
$output .= «<» . htmlspecialchars ( $key ). » type=’bool’>» .( $val ? «true» : «false» ).
«</» . htmlspecialchars ( $key ). «>\n» ; break;
case «integer» :
$output .= «<» . htmlspecialchars ( $key ). » type=’integer’>» .
htmlspecialchars ( $val ). «</» . htmlspecialchars ( $key ). «>\n» ; break;
case «double» :
$output .= «<» . htmlspecialchars ( $key ). » type=’double’>» .
htmlspecialchars ( $val ). «</» . htmlspecialchars ( $key ). «>\n» ; break;
case «string» :
$output .= «<» . htmlspecialchars ( $key ). » type=’string’ size='» . strlen ( $val ). «‘>» .
htmlspecialchars ( $val ). «</» . htmlspecialchars ( $key ). «>\n» ; break;
default:
$output .= «<» . htmlspecialchars ( $key ). » type=’unknown’>» . gettype ( $val ).
«</» . htmlspecialchars ( $key ). «>\n» ; break;
>
>
if ( $first ) $output .= «</data>\n» ;
return $output ;
>
A slight amendment to Matt’s awesome print_r_reverse function (Thank You, a life-saver — data recovery 🙂 . If the output is copied from a Windows system, the end of lines may include the return character «\r» and so the scalar (string) elements will include a trailing «\r» character that isn’t suppose to be there. To resolve, replace the first line in the function with.
<?php $lines = preg_split ( ‘#\r?\n#’ , trim ( $in )); ?>
This will work for both cases (Linux and Windows).
I include the entire function below for completeness, but all credit to Matt, the original author, Thank You.
<?php
//Author: Matt (http://us3.php.net/print_r)
function print_r_reverse ( $in ) <
$lines = preg_split ( ‘#\r?\n#’ , trim ( $in ));
if ( trim ( $lines [ 0 ]) != ‘Array’ ) <
// bottomed out to something that isn’t an array
return $in ;
> else <
// this is an array, lets parse it
if ( preg_match ( «/(\s<5,>)\(/» , $lines [ 1 ], $match )) <
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match [ 1 ];
$spaces_length = strlen ( $spaces );
$lines_total = count ( $lines );
for ( $i = 0 ; $i < $lines_total ; $i ++) <
if ( substr ( $lines [ $i ], 0 , $spaces_length ) == $spaces ) <
$lines [ $i ] = substr ( $lines [ $i ], $spaces_length );
>
>
>
array_shift ( $lines ); // Array
array_shift ( $lines ); // (
array_pop ( $lines ); // )
$in = implode ( «\n» , $lines );
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all ( «/^\s<4>\[(.+?)\] \=\> /m» , $in , $matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
$pos = array();
$previous_key = » ;
$in_length = strlen ( $in );
// store the following in $pos:
// array with key = key of the parsed array’s item
// value = array(start position in $in, $end position in $in)
foreach ( $matches as $match ) <
$key = $match [ 1 ][ 0 ];
$start = $match [ 0 ][ 1 ] + strlen ( $match [ 0 ][ 0 ]);
$pos [ $key ] = array( $start , $in_length );
if ( $previous_key != » ) $pos [ $previous_key ][ 1 ] = $match [ 0 ][ 1 ] — 1 ;
$previous_key = $key ;
>
$ret = array();
foreach ( $pos as $key => $where ) <
// recursively see if the parsed out value is an array too
$ret [ $key ] = print_r_reverse ( substr ( $in , $where [ 0 ], $where [ 1 ] — $where [ 0 ]));
>
return $ret ;
>
>
?>
I was having problems using print_r because I didn’t like the fact that if tags where included in the array it would still be parsed by the browsers.
Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser’s «view source» or CLI.
$MyArray [ 0 ]= «<div align=’center’>My Text</div>» ;
echo «<pre>» . htmlspecialchars ( print_r ( $MyArray , true )). «</pre>» ;
How to print Console.log in PHP
![]()
The console.log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
MDN WEB DOCS
If you are a Frontend Developer or who use web browser, you need to know well about this method. As a junior web dev, I also love printing with this method but sometime I meet obstacle.
Work with PHP
My company has a website that made by WordPress. So i need to fix bug in in PHP environment the first thing i need to find is this.
“How can i debug with console.log() ”
For this reason, I decided to wrap up that method today.
How can i print Console.log( ) in PHP?
The principle is simple. PHP is a backend environment, it draws code into pieces.
If we want to write console.log( ) like above then,
So easy right? If it is little hard to understand than you can break down it.
This way, you will be able to understand the principle of PHP to output pieces one by one.
PHP console log — How to log to console using PHP
Sometimes, you need to log your PHP variable values to the browser console for debugging purposes.
Unfortunately, the PHP echo function will render output in the browser’s window or the command line terminal, depending on where the PHP script is executed.
In this tutorial, you will learn how to write a log to the browser console using PHP.
Write a log to the console using PHP
As a server-side scripting language, PHP doesn’t have a built-in function to interact with the browser’s API directly.
To write logs to the browser console, you need the help of JavaScript like this:
Running the PHP script below will produce the following HTML output:
By adding <script> tag to the echo function’s argument, you will generate a <script> tag in the rendered HTML.
This way, the PHP variable $data value will be logged to the browser console as shown below:
Because the echo function outputs a string , you will receive a warning when you log an array, and a fatal error when you log an object.
To print arrays and objects successfully, call the json_encode() function to transform the data as follows:
Now you can print variable values to the console, including an array and an object.
To avoid repeating the code each time you need to log to the console, you can create a reusable function named log_to_console() as shown below:
Let’s test the log_to_console() function and see its output:
The output in the console is as follows:
To keep the array and object format in the console, you need to remove the quotation mark around the console.log() argument.
You can add a second parameter to the log_to_console() function that decides whether a quote will be added to the output or not:
Then, you need to pass a second argument when you call the log_to_console() function to log arrays and objects:
Now the output will be as follows:
That looks much better than the previous output.
PHP console log using the script tag
Depending on your preference, you can also log your PHP values using the <script> tag in your PHP view files like this:
The <?= ?> tag is the shorthand syntax for the echo function.
If the function above doesn’t work, check the quotation marks you used around your variable and console.log() function.
If the PHP variable use double quotes, the console.log() function needs to use the single quote mark, and vice versa.
For arrays and objects, you can omit the quotes inside the console.log() function so that the browser doesn’t log them as strings.
PHP console log using the PHPDebugConsole library
Besides writing your own function, PHP also has open source libraries to write logs to the console.
Two of the most popular libraries are PHPDebugConsole and PHPConsole. Let’s see how PHPDebugConsole works.
First, you need to install the PHPDebugConsole library in your project. You can download the release zip or you can use Composer.
Here’s how to install it using Composer:
Note that you need to explicitly use version 3 because version 2 doesn’t generate output to the browser console.
Next, import the library into your code using require and set the debug configuration as follows:
Now you can log into the browser console as follows:
And here’s the output of the code above:
By default, the PHPDebugConsole library will generate an output to the HTML page.
This is changed by setting the route option to script when instantiating the Debug class as shown above.
The PHPDebugConsole has many options to help you debug PHP code.
It can also be integrated with PHP frameworks like Laravel, Symfony, and Yii, so head over to PHPDebugConsole documentation if you’re interested to try it out.
Conclusion
To generate a log output using PHP, you need to create a custom function that calls the JavaScript console.log() function.
The code for the function is as follows:
Alternatively, you can also install the PHPDebugConsole library to your PHP project so that you can generate a more detailed output.
But for simple projects, using PHPDebugConsole may be too much, so you can stick with the log_to_console() function created above.
Now you’ve learned how to log to the console using PHP. Good work!
Get 98 PHP Snippets Book for FREE
98 PHP snippets that you can use in various scenarios
Save 1000+ hours of research and 10x your productivity
About
Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.
Free Code Snippets Book
Get my FREE code snippets Book to 10x your productivity here

report this ad