How can I write to the console in PHP?


Is it possible write a string or log into the console?

What I mean

Just like in JSP, if we print something like system.out.println("some"), it will be there at the console, not at a page.

8/3/2019 1:03:42 PM

Accepted Answer


On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.


However if you are using Chrome there is a PHP debugging tool called Chrome Logger or webug (webug has problems with the order of logs).

More recently Clockwork is in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4 and Slim 2 and support can be added via its extensible API.

Using Xdebug

A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.

9/14/2018 6:21:09 PM

If you're looking for a simple approach, echo as JSON:

    console.log(<?= json_encode($foo); ?>);

By default, all output goes to stdout, which is the HTTP response or the console, depending on whether your script is run by Apache or manually on the command line. But you can use error_log for logging and various I/O streams can be written to with fwrite.


Try the following. It is working:

echo("<script>console.log('PHP: " . $data . "');</script>");

"<div display='none'>
    <script type='text/javascript'>
        console.log('console log message');

Creates a


with the


so that the div is not displayed, but the


function is created in javascript. So you get the message in the console.


As the author of the linked webpage in the popular answer, I would like to add my last version of this simple helper function. It is much more solid.

I use json_encode() to make a check for if the variable type is not necessary and also add a buffer to solve problems with frameworks. There not have a solid return or excessive usage of header().

 * Simple helper to debug to the console
 * @param $data object, array, string $data
 * @param $context string  Optional a description.
 * @return string
function debug_to_console($data, $context = 'Debug in Console') {

    // Buffering to solve problems frameworks, like header() in this and not a solid return.

    $output  = '\'' . $context . ':\');';
    $output .= 'console.log(' . json_encode($data) . ');';
    $output  = sprintf('<script>%s</script>', $output);

    echo $output;


// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];

Screenshot of the result

Also a simple example as an image to understand it much easier:

Enter image description here