404

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Labeeb Panampullan
  • 34,521
  • 28
  • 94
  • 112
  • If you use WordPress, I got a [solution](https://stackoverflow.com/questions/33265780/how-to-print-to-console-from-a-php-file-in-wordpress/67449528#67449528) for you. – Martin Braun May 08 '21 at 16:38

30 Answers30

529

Or you use the trick from PHP Debug to console.

First you need a little PHP helper function

function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}

Then you can use it like this:

debug_to_console("Test");

This will create an output like this:

Debug Objects: Test
bueltge
  • 2,294
  • 1
  • 29
  • 40
Senador
  • 5,580
  • 2
  • 15
  • 12
  • 7
    In FireFox v27 it outputs `"Debug Objects: " . $data . ""` – Mawg says reinstate Monica Mar 23 '14 at 22:11
  • The only way to make this more useful would be to do a variable $name : 'data' pair in the log. Nice function though. – Imperative Jul 30 '14 at 18:13
  • perfect solution. just swap `console.log` FOR `alert` and you create an alert box, which can be useful if you want to know exactly when (in a series of events) something(s) is(are) happening. – tony gil Dec 06 '14 at 12:27
  • 16
    @Mawg (and the people who upvoted that comment): If `$data` appears in the output, then you haven't typed the function exactly as shown. Look carefully at your single and double quotes, to make sure they match the code above. `$data` is a php variable; by the time the page is sent to browser, that php variable will have been replaced by the parameter passed to `debug_to_console`. The browser should never see `$data`. (If you look at `page source` in browser, it should not say `$data`.) – ToolmakerSteve Jun 15 '15 at 17:34
  • What do you do with the resulting "Cannot modify header information -" errors? – Magne Jul 04 '15 at 13:03
  • If the faulty PHP script is generating an AJAX response or a image (anything that is not a web page being rendered) that won't work. – Paolo Jul 29 '15 at 14:20
  • Doesn't work at all with debugging JSON requests, as it adds markup to the response – Brian Leishman Aug 24 '15 at 13:26
  • Useful but doesn't work in its current form for an associated array. Or as someone mentioned a JSON request. – mmv_sat Sep 22 '15 at 17:03
  • 1
    Thanks for the hint to my post. But the time and the knowledge has changed, the function also ;) I have it update now. – bueltge May 13 '16 at 18:09
  • @CubeJockey OK, now added as separate answer. Maybe it's helps other readers. But I don't understand it, why is it not fit as an edit to this context. – bueltge May 13 '16 at 20:06
  • 2
    OP states he wanted to print to standard output, not to html/js console. – beppe9000 Feb 14 '17 at 16:04
  • 4
    So, in other words, the answer is this: echo ""; – Christine Jul 29 '17 at 17:06
  • @Magne Nothing. The moment that echo is read all header() calls will fail. This answer is not suited for those types of scenarios. – Steven Serrano Jan 10 '19 at 16:03
  • This is sliced bread. Easy to implement, use,. and remove--at least in Chrome. – JayJay123 Oct 15 '20 at 08:14
  • thank worked well echo ""; – Erhan Demirci Dec 04 '20 at 15:57
  • echo ""; to fix in case single quote in the property value of object – Duc Nguyen May 30 '22 at 08:00
  • note the output might be the ajax request and then this doesnt work – luky May 03 '23 at 08:29
155

Firefox

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.

Chrome

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.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Malachi
  • 33,142
  • 18
  • 63
  • 96
  • 6
    There's also a Safari extension for debugging PHP called Xdebug Helper. I installed it from this page: https://extensions.apple.com/#tab – Mark Mckelvie Feb 27 '13 at 19:12
  • 1
    I think the best debugging extension for Google Chrome is PHP Console https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef – barbushin Dec 09 '13 at 04:26
  • Nothing for Internet Explorer? I realize it's not number one, but it's still up there... – dsimer Apr 24 '14 at 13:50
  • 3
    Fire PHP link is dead – Brian Leishman Aug 24 '15 at 13:27
  • 14
    echo ""; – Azmat Karim Khan Aug 06 '16 at 17:33
  • 5
    OP states he wanted to print to standard output, not to html/js console. – beppe9000 Feb 14 '17 at 16:03
  • 7
    FirePHP is officially dead. – TimSparrow Mar 24 '17 at 09:34
  • X-debug and similar is a huge turn off for PHP. Should be noted and discussed more in so far as the debugging tools are difficult, clunky, and unreliable. In other languages I can build a debugger in a few lines, filter the terminal output down, and really get into things. PHP makes these tasks hard. Today is a day I am reminded of that having to echo brute force output through a JSON API only to be picked up in the browser console error. Boo PHP, c'mon. – Marc Dec 28 '22 at 18:52
87

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

<script>
    console.log(<?= json_encode($foo); ?>);
</script>
yckart
  • 32,460
  • 9
  • 122
  • 129
Travis
  • 1,463
  • 11
  • 12
  • 5
    This adds a bit more context: `function debug_log( $object=null, $label=null ){ $message = json_encode($object, JSON_PRETTY_PRINT); $label = "Debug" . ($label ? " ($label): " : ': '); echo ""; }` – robrecord Jan 16 '17 at 08:16
  • 1
    OP states he wanted to print to standard output, not to html/js console. – beppe9000 Feb 14 '17 at 16:04
  • @beppe9000 That is incorrect. The OP asks if he can write from PHP to the console. Quote: "Is it possible write string or log into the console?" – Dawson Irvine Feb 17 '19 at 20:26
  • with this you can avoid var_dumps and similar. Works great and the console lets you toggle the json in a nice way. – Mbotet Jun 11 '19 at 10:42
  • This was a very elegant solution – schizoid04 Oct 27 '22 at 18:00
53

Try the following. It is working:

echo("<script>console.log('PHP: " . $data . "');</script>");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mandy
  • 547
  • 4
  • 3
  • 5
    This is not very real time, since php sends all the page once it's finished processing. Furthermore, if there is an error in the php file, you won't get to see any of the logs even, because it will only return an error page, thus ignoring your earlier prints. – Miro Markaravanes Mar 12 '14 at 02:38
  • 1
    I'd like to point out that @MiroMarkaravanes is absolutely correct - fatal errors can prevent your console.log from outputting unless you make sure to handle/catch every single possible error. Especially when using output buffering - if your buffer doesn't make it to the screen, neither does your console.log output. It's something to be mindful of. – whoshotdk Aug 24 '16 at 14:26
  • 1
    OP states he wanted to print to standard output, not to html/js console. – beppe9000 Feb 14 '17 at 16:05
  • I got an 'Array' output, fixed with `echo("");` – David B Dec 31 '20 at 04:46
50

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.

nikc.org
  • 16,462
  • 6
  • 50
  • 83
  • 12
    Thanks, `error_log` is what I needed to output to the terminal from the [PHP built-in web server](http://www.php.net/manual/en/features.commandline.webserver.php) – Martín Coll Jan 20 '14 at 20:43
32

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 check if the variable type is unnecessary and 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.
    ob_start();

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

    echo $output;
}

Usage

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

Screenshot of the result

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

Enter image description here

bueltge
  • 2,294
  • 1
  • 29
  • 40
  • While I _do_ like this idea, could you confirm that it would not be suitable for Ajax requests? – Mawg says reinstate Monica Jul 04 '16 at 10:02
  • 2
    Yes, it is pure static php, not Ajax. – bueltge Jul 04 '16 at 10:29
  • But, it seems to be adding HML/JS code ot a page body - and my Ajax returns no page body. Sorry, but I don't undertsand & thansk for trying ot help me – Mawg says reinstate Monica Jul 04 '16 at 10:34
  • 1
    You should trigger the helper function before request the ajax call, then you get also a result in the console. – bueltge Jul 04 '16 at 10:56
  • So I put a variable in there and each Character ended up on its own line. Kind of curious as to why its doing that? Never used console.info – yardpenalty.com Oct 21 '16 at 13:28
  • So it seems it did the \n after each char when I passed a numeric value and not a string I think. – yardpenalty.com Oct 21 '16 at 14:20
  • That's a formatting point of the console, not from the helper function. – bueltge Oct 22 '16 at 13:42
  • OP states he wanted to print to server-side terminal / standard output, not to html/js console. – beppe9000 Feb 14 '17 at 16:06
  • What do you mean by *"There not have a solid return or excessive usage of `header()`."*. [Homonym error](http://www.wikihow.com/Use-There,-Their-and-They%27re)? It seems incomprehensible. – Peter Mortensen Aug 03 '19 at 14:03
  • I mean that each method should have a solid return type, always string; no mix from different types. So this function is an helper and don't have this requirement. In the context of header() I mean the time in this context. header need more data and don't helps here to get helping output for debugging. Thanks for your edit, really helpful. – bueltge Aug 13 '19 at 13:20
  • Why console.log and console.info, both - why not use one or the other? They both do the same thing and both write to stdout. – Chiwda Jan 30 '22 at 07:02
  • Yes, you have right. It is more in case of meta language, Info - information and log - logging, details behind in this thread are helpful. https://stackoverflow.com/questions/25532778/node-js-console-log-vs-console-info – bueltge Jan 31 '22 at 08:09
22
$variable = "Variable";
echo "<script>console.log('$variable');</script>";

PHP and JavaScript interaction.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0DAYanc
  • 357
  • 2
  • 5
  • 1
    An explanation would be in order. Can you elaborate ([by editing your answer](https://stackoverflow.com/posts/45496116/edit), not by answering in comments)? – Peter Mortensen Aug 03 '19 at 14:18
20

I think it can be used --

function jsLogs($data, $isExit) {
    $html = "";
    $coll;

    if (is_array($data) || is_object($data)) {
        $coll = json_encode($data);
    } else {
        $coll = $data;
    }

    $html = "<script id='jsLogs'>console.log('PHP: ${coll}');</script>";

    echo($html);

    if ($isExit) exit();
}

# For String
jsLogs("Testing string"); #PHP: Testing string

# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]

# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
Pankaj Bisht
  • 986
  • 1
  • 8
  • 27
20
echo 
"<div display='none'>
    <script type='text/javascript'>
        console.log('console log message');
    </script>
</div>";

Creates a

<div>

with the

display="none"

so that the div is not displayed, but the

console.log()

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

Pankaj Bisht
  • 986
  • 1
  • 8
  • 27
Neo
  • 755
  • 1
  • 10
  • 24
  • 3
    Technically this is the right answer to the initial question - how to write to the browser console from PHP. But I think the author is trying to debug PHP so there are better options. It should not be downvoted though, strictly speaking this is a correct answer. – Rolf Oct 25 '17 at 11:58
  • 1
    i certainly just found it incredibly helpful! – albert Feb 04 '18 at 02:01
  • Keeping it simple, this solution is great because it is self explanatory. Especially when you have a lot to chew at the same time as I am going through now. – Olu Adabonyan Feb 01 '19 at 17:19
  • 2
    I don't understand why you even need a `div`. if you just have a ` – Cave Johnson Mar 10 '19 at 01:42
  • 1
    Also, if your error message is stored in a variable, or if it contains quotation marks, you would do well to wrap the message in a call to `json.encode` so that quotation marks do not break your line of code. For example: `echo ""; ` – SherylHohman Jun 01 '19 at 19:05
15

Some great answers that add more depth; but I needed something simpler and more like the JavaScript console.log() command.

I use PHP in a lot of "gathering data and turn into XML" in Ajax applications. The JavaScript console.log doesn't work in that case; it breaks the XML output.

Xdebug, etc. had similar issues.

My solution in Windows:

  • Setup a .txt file that is somewhat easily to get to and writable
  • Set the PHP error_log variable in the .ini file to write to that file
  • Open the file in Windows File Explorer and open a preview pane for it
  • Use the error_log('myTest'); PHP command to send messages

This solution is simple and meets my needs most of the time. Standard PHP, and the preview pane automatically updates every time PHP writes to it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Klompenrunner
  • 723
  • 7
  • 13
  • Would wrapping the message in `json_encode` also solve the issue? If so, it may be that quotation marks within the message interfered with quotation marks in the script. (for example: `echo "";`). If not, I'm curious what the issue was that caused the console.log script to break, and how/why your solution fixed that. Your solution is good - I'm just trying to learn more about the conditions that caused `console.log` or xml output to break. In many cases, an error log as you did is much better than a quick `console.log`. – SherylHohman Jun 01 '19 at 19:16
11

I find this helpful:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        $output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';

        echo $output;
    }
}

And use it like:

<?php
    $debug = 5; // All lower and equal priority logs will be displayed
    console('Important', 1 , $debug);
    console('Less Important', 2 , $debug);
    console('Even Less Important', 5 , $debug);
    console('Again Important', 1 , $debug);
?>

Which outputs in console:

Important
 Less Important
     Even Less Important
Again Important

And you can switch off less important logs by limiting them using the $debug value.

zee
  • 359
  • 3
  • 16
  • so if you call `console('Even Less Important' ,6 , $debug);` this won't be displayed in the console? why so? is anything above 5 not displayed – HattrickNZ Apr 21 '16 at 23:19
  • 2
    @HattrickNZ This is to allow you to have different levels of log messages. If you are debugging you might want to show a very chatty stream of message with lots of info, however during normal operations you might set debug to 1 so you only get the most important errors/log items displayed. Its up to you to decide what items are important when writing the code. – Toby Allen Apr 23 '16 at 07:16
  • OP states he wanted to print to standard output, not to html/js console. – beppe9000 Feb 14 '17 at 16:05
  • @beppe9000, not really. You edited the OPs question changing it completely. http://stackoverflow.com/posts/4323411/revisions – zee Feb 15 '17 at 10:11
  • @zee If you read his example, JSP's `system.out.println("some")` actually [prints to the standard output](http://stackoverflow.com/a/10396394/3389585) and not to page. – beppe9000 Feb 15 '17 at 11:20
  • 1
    Yes, but repeated code (redundancy) - ought to be refactored: `$output = '';`. Only `implode(",", $data)` and `$data` is different. – Peter Mortensen Aug 03 '19 at 13:51
  • 1
    @Peter Mortensen - true story! Edited this over 4yo post! :) – zee Aug 03 '19 at 20:23
10

I think best solution is to use error_log(content) This is output

Edit 2022:

So I’ve discovered way better way and thats file_put_contents("php://stdout", content)

It writes without the logging info

random-forest-cat
  • 33,652
  • 11
  • 120
  • 99
Majkel
  • 131
  • 2
  • 5
9

Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}
Carlos Lugo
  • 99
  • 1
  • 5
8
function phpconsole($label='var', $x) {
    ?>
    <script type="text/javascript">
        console.log('<?php echo ($label)?>');
        console.log('<?php echo json_encode($x)?>');
    </script>
    <?php
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ashraf mohammed
  • 1,322
  • 15
  • 20
8

For Chrome there is an extension called Chrome Logger allowing to log PHP messages.

The Firefox DevTools even have integrated support for the Chrome Logger protocol.

To enable the logging, you just need to save the 'ChromePhp.php' file in your project. Then it can be used like this:

include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');

Example taken from the GitHub page.

The output may then look like this:

Server log within Firefox DevTools

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
7

If you want write to the PHP log file, and not the JavaScript console you can use this:

error_log("This is logged only to the PHP log")

Reference: error_log

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dan Green-Leipciger
  • 3,776
  • 1
  • 19
  • 29
5

There is also a great Google Chrome extension, PHP Console, with a PHP library that allows you to:

  • See errors and exceptions in the Chrome JavaScript console and in the notification popups.
  • Dump any type of variable.
  • Execute PHP code remotely.
  • Protect access by password.
  • Group console logs by request.
  • Jump to error file:line in your text editor.
  • Copy error/debug data to the clipboard (for testers).
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
barbushin
  • 5,165
  • 5
  • 37
  • 43
  • 1
    My preferred method of writing PHP errors, exception and user-defined debugging output to the JS console. I've been using it for years - highly reliable and kept up-to-date with PHP revisions. I wouldn't use anything else. – Velojet Sep 27 '15 at 21:07
  • Been using for years. Appears now fully dead. Link is 404. :-( – rmirabelle Oct 26 '20 at 22:46
5

Here is my solution, the good thing about this one is that you can pass as many params as you like.

function console_log()
{
    $js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
        ');';
    $js_code = '<script>' . $js_code . '</script>';
    echo $js_code;
}

Call it this way

console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);

Now you should be able to see output in your console, happy coding :)

Imran Zahoor
  • 2,521
  • 1
  • 28
  • 38
3

Any of these two are working:

<?php
    $five = 5;
    $six = 6;
?>
<script>
    console.log(<?php echo $five + $six ?>);
</script>


<?php
    $five = 5;
    $six = 6;
    echo("<script>console.log($five + $six);</script>");
?>
roybraym
  • 69
  • 3
3

I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.

I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:

function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}

Usage is as follows:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Clinton
  • 1,111
  • 1
  • 14
  • 21
  • 1
    At that point you might as well use a transient? `set_transient('my_debug_transient',$this);` and read it out from the db, no messing with various browser and JSON etc issues. Or read it in with `get_transient( ... )` then add some content at the end. – user3445853 Jul 28 '20 at 13:53
3

For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.

If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.

Frank Forte
  • 2,031
  • 20
  • 19
  • [FirePHP is no longer viable](https://stackoverflow.com/questions/4323411/how-can-i-write-to-the-console-in-php/45215947#45215947). – Peter Mortensen Aug 03 '19 at 14:22
3

Clean, fast and simple without useless code:

function consolelog($data) {
    echo "<script>console.log('".$data."');</script>";
}
Marco Concas
  • 1,665
  • 20
  • 25
3

Short and simply with printf and json_encode:

function console_log($data) {
    printf('<script>console.log(%s);</script>', json_encode($data));
}
Wallace Vizerra
  • 3,382
  • 2
  • 28
  • 29
2

I have abandoned all of the above in favour of Debugger & Logger. I cannot praise it enough!

Just click on one of the tabs at top right, or on the "click here" to expand/hide.

Notice the different "categories". You can click any array to expand/collapse it.

From the web page

Main features:

  • Show globals variables ($GLOBALS, $_POST, $_GET, $_COOKIE, etc.)
  • Show PHP version and loaded extensions
  • Replace PHP built in error handler
  • Log SQL queries
  • Monitor code and SQL queries execution time
  • Inspect variables for changes
  • Function calls tracing
  • Code coverage analysis to check which lines of script where executed
  • Dump of all types of variable
  • File inspector with code highlighter to view source code
  • Send messages to JavaScript console (Chrome only), for Ajax scripts

Enter image description here

Community
  • 1
  • 1
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • Hi. Is there a newest fork or similar tool more up to date and currently maintained? – Metafaniel Nov 28 '18 at 23:43
  • I didn't code it, so for the newest fork, I guess just go to GitHub? For alternatives, ask at https://softwarerecs.stackexchange.com/ and we will help you. – Mawg says reinstate Monica Nov 29 '18 at 08:28
  • 1
    @MawgHi, thanks. I asked because [phptoolcase Github](https://github.com/ifsale/PhpToolCase) and the forks listed there haven't been updated in 5 years. Thanks for the other StackExchange site. I just found [Clockwork](https://underground.works/clockwork/). I wonder if it's similar or better... – Metafaniel Nov 29 '18 at 23:56
  • And thank ***you*** for Clockwork. It looks excellent (just a pity that I don't use any of those frameworks (I wonder if that's how it can dump database queries - by hooking the framework)). Well worth investigating. (+1) – Mawg says reinstate Monica Nov 30 '18 at 07:30
2

As of 2017, Firebug and hence FirePHP has been disabled.

I wrote some little modifications to the ChromePHP tool to allow seamless migration from FirePHP to Firebug for debugging via the console.

This article explains in clear easy steps

Migrate from FirePHP to ChromePHP in 5 minutes (without breaking existing code)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kudehinbu Oluwaponle
  • 1,045
  • 11
  • 11
2

I might be late for a party, but I was looking for an implementation of logging function which:

  • takes a variable number of comma separated arguments, just like javascript console.log(),
  • gives a formatted output (not just a serialized string),
  • is distinguishable from a common javascript console.log().

So the output looks like that:

enter image description here

(The snippet below is tested on php 7.2.11. I'm not sure about its php backward compatibility. It can be an issue for javascript as well (in a term of old browsers), because it creates a trailing comma after console.log() arguments – which is not legal until ES 2017.)

<?php

function console_log(...$args)
{
    $args_as_json = array_map(function ($item) {
        return json_encode($item);
    }, $args);

    $js_code = "<script>console.log('%c  log from PHP: ','background: #474A8A; color: #B0B3D6; line-height: 2',";
    foreach ($args_as_json as $arg) {
        $js_code .= "{$arg},";
    }
    $js_code .= ")</script>";

    echo $js_code;
}

$list = ['foo', 'bar'];
$obj = new stdClass();
$obj->first_name = 'John';
$obj->last_name = 'Johnson';

echo console_log($list, 'Hello World', 123, $obj);

?>
HynekS
  • 2,738
  • 1
  • 19
  • 34
2

Though this is an old question, I've been looking for this. Here's my compilation of some solutions answered here and some other ideas found elsewhere to get a one-size-fits-all solution.

CODE :

    // Post to browser console
    function console($data, $is_error = false, $file = false, $ln = false) {
        if(!function_exists('console_wer')) {
            function console_wer($data, $is_error = false, $bctr, $file, $ln) {
                echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); });  }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
            }
        }
        return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
    }
    
    //PHP Exceptions handler
    function exceptions_to_console($svr, $str, $file, $ln) {
        if(!function_exists('severity_tag')) {
            function severity_tag($svr) {
                $names = [];
                $consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
                foreach ($consts as $code => $name) {
                    if ($svr & $code) $names []= $name;
                }
                return join(' | ', $names);
            }
        }
        if (error_reporting() == 0) {
            return false;
        }
        if(error_reporting() & $svr) {
            console(severity_tag($svr).' : '.$str, true, $file, $ln);
        }
    }

    // Divert php error traffic
    error_reporting(E_ALL);  
    ini_set("display_errors", "1");
    set_error_handler('exceptions_to_console');

TESTS & USAGE :

Usage is simple. Include first function for posting to console manually. Use second function for diverting php exception handling. Following test should give an idea.

    // Test 1 - Auto - Handle php error and report error with severity info
    $a[1] = 'jfksjfks';
    try {
          $b = $a[0];
    } catch (Exception $e) {
          echo "jsdlkjflsjfkjl";
    }

    // Test 2 - Manual - Without explicitly providing file name and line no.
          console(array(1 => "Hi", array("hellow")), false);
    
    // Test 3 - Manual - Explicitly providing file name and line no.
          console(array(1 => "Error", array($some_result)), true, 'my file', 2);
    
    // Test 4 - Manual - Explicitly providing file name only.
          console(array(1 => "Error", array($some_result)), true, 'my file');
    

EXPLANATION :

  • The function console($data, $is_error, $file, $fn) takes string or array as first argument and posts it on console using js inserts.

  • Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false.

  • Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace() to fetch them for us.

  • Next function exceptions_to_console($svr, $str, $file, $ln) has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code) to provide more info on error.

NOTICE :

  • Above code uses JS functions and methods that are not available in older browsers. For compatibility with older versions, it needs replacements.

  • Above code is for testing environments, where you alone have access to the site. Do not use this in live (production) websites.

SUGGESTIONS :

  • First function console() threw some notices, so I've wrapped them within another function and called it using error control operator '@'. This can be avoided if you didn't mind the notices.

  • Last but not least, alerts popping up can be annoying while coding. For this I'm using this beep (found in solution : https://stackoverflow.com/a/23395136/6060602) instead of popup alerts. It's pretty cool and possibilities are endless, you can play your favorite tunes and make coding less stressful.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Ajay Singh
  • 692
  • 8
  • 19
1

Here's a handy function. It is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP

Note, you can use tags as well by passing 'TAG-YourTag', and it will be applied until another tag is read, for example, 'TAG-YourNextTag'

/*
 *  Brief:         Print to console.log() from PHP
 *
 *  Description:   Print as many strings,arrays, objects, and
 *                 other data types to console.log from PHP.
 *
 *                 To use, just call consoleLog($data1, $data2, ... $dataN)
 *                 and each dataI will be sent to console.log - note
 *                 that you can pass as many data as you want an
 *                 this will still work.
 *
 *                 This is very powerful as it shows the entire
 *                 contents of objects and arrays that can be
 *                 read inside of the browser console log.
 *
 *                 A tag can be set by passing a string that has the
 *                 prefix TAG- as one of the arguments. Everytime a
 *                 string with the TAG- prefix is detected, the tag
 *                 is updated. This allows you to pass a tag that is
 *                 applied to all data until it reaches another tag,
 *                 which can then be applied to all data after it.
 *
 *                 Example:
 *
 *                 consoleLog('TAG-FirstTag', $data, $data2, 'TAG-SecTag, $data3);
 *
 *                 Result:
 *                     FirstTag '...data...'
 *                     FirstTag '...data2...'
 *                     SecTag   '...data3...'
 */
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){
            if(is_string($arg) && strtolower(substr($arg, 0, 4)) === 'tag-'){
                $tag = substr($arg, 4);
            }else{
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('" . $tag . " " . $arg . "');</script>";
            }
        }
    }
}

NOTE: func_num_args() and func_num_args() are PHP functions for reading a dynamic number of input arguments, and allow this function to have infinitely many console.log requests from one function call.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Sprague
  • 3,158
  • 33
  • 24
0

Use:

function console_log($data) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if (is_array($data))
        $dataPart = implode(',', $data);
    else
        $dataPart = $data;

    $toSplit = $caller['file'])) . ':' .
               $caller['line'] . ' => ' . $dataPart

    error_log(end(split('/', $toSplit));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
btm1
  • 3,866
  • 2
  • 23
  • 26
0

in start code...

error_reporting(-1);
ini_set('display_errors', 'On'); 

it work

it work

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Vladimir
  • 11
  • 1