How can I write to the console in PHP?

1,401,702

Solution 1

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.

Solution 2

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

Solution 3

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

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

Solution 4

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.

Solution 5

Try the following. It is working:

echo("<script>console.log('PHP: " . $data . "');</script>");
Share:
1,401,702
Labeeb Panampullan
Author by

Labeeb Panampullan

Updated on January 04, 2022

Comments

  • Labeeb Panampullan
    Labeeb Panampullan over 2 years

    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.

  • Mark Mckelvie
    Mark Mckelvie over 11 years
    There's also a Safari extension for debugging PHP called Xdebug Helper. I installed it from this page: extensions.apple.com/#tab
  • barbushin
    barbushin over 10 years
    I think the best debugging extension for Google Chrome is PHP Console chrome.google.com/webstore/detail/php-console/…
  • Martín Coll
    Martín Coll over 10 years
    Thanks, error_log is what I needed to output to the terminal from the PHP built-in web server
  • Miro Markaravanes
    Miro Markaravanes over 10 years
    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.
  • Mawg says reinstate Monica
    Mawg says reinstate Monica over 10 years
    In FireFox v27 it outputs "Debug Objects: " . $data . ""
  • dsimer
    dsimer about 10 years
    Nothing for Internet Explorer? I realize it's not number one, but it's still up there...
  • Imperative
    Imperative almost 10 years
    The only way to make this more useful would be to do a variable $name : 'data' pair in the log. Nice function though.
  • tony gil
    tony gil over 9 years
    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.
  • ToolmakerSteve
    ToolmakerSteve about 9 years
    @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.)
  • Magne
    Magne almost 9 years
    What do you do with the resulting "Cannot modify header information -" errors?
  • Paolo
    Paolo almost 9 years
    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.
  • Brian Leishman
    Brian Leishman almost 9 years
    Doesn't work at all with debugging JSON requests, as it adds markup to the response
  • Brian Leishman
    Brian Leishman almost 9 years
    Fire PHP link is dead
  • mmv_sat
    mmv_sat almost 9 years
    Useful but doesn't work in its current form for an associated array. Or as someone mentioned a JSON request.
  • Velojet
    Velojet almost 9 years
    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.
  • HattrickNZ
    HattrickNZ about 8 years
    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
  • Toby Allen
    Toby Allen about 8 years
    @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.
  • bueltge
    bueltge about 8 years
    You should add a hint about your idea and solution. Also the source have unused source.
  • bueltge
    bueltge about 8 years
    Thanks for the hint to my post. But the time and the knowledge has changed, the function also ;) I have it update now.
  • bueltge
    bueltge about 8 years
    @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.
  • Mawg says reinstate Monica
    Mawg says reinstate Monica almost 8 years
    While I do like this idea, could you confirm that it would not be suitable for Ajax requests?
  • bueltge
    bueltge almost 8 years
    Yes, it is pure static php, not Ajax.
  • Mawg says reinstate Monica
    Mawg says reinstate Monica almost 8 years
    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
  • bueltge
    bueltge almost 8 years
    You should trigger the helper function before request the ajax call, then you get also a result in the console.
  • Azmat Karim Khan
    Azmat Karim Khan almost 8 years
    echo "<script> console.log('PHP: ',",get_option("slides_data"),");</script>";
  • whoshotdk
    whoshotdk almost 8 years
    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.
  • yardpenalty.com
    yardpenalty.com over 7 years
    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
    yardpenalty.com over 7 years
    So it seems it did the \n after each char when I passed a numeric value and not a string I think.
  • bueltge
    bueltge over 7 years
    That's a formatting point of the console, not from the helper function.
  • padawanTony
    padawanTony over 7 years
    You can also install it via composer: "ccampbell/chromephp": "*"
  • robrecord
    robrecord over 7 years
    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 "<script>console.log(\"$label\", $message);</script>"; }
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to server-side terminal / standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to server-side terminal / standard output, not to html/js console.
  • beppe9000
    beppe9000 over 7 years
    OP states he wanted to print to server-side terminal / standard output, not to html/js console.
  • zee
    zee over 7 years
    @beppe9000, not really. You edited the OPs question changing it completely. stackoverflow.com/posts/4323411/revisions
  • beppe9000
    beppe9000 over 7 years
    @zee If you read his example, JSP's system.out.println("some") actually prints to the standard output and not to page.
  • TimSparrow
    TimSparrow over 7 years
    FirePHP is officially dead.
  • Christine
    Christine almost 7 years
    So, in other words, the answer is this: echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
  • Rolf
    Rolf over 6 years
    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.
  • albert
    albert over 6 years
    i certainly just found it incredibly helpful!
  • Hayden Thring
    Hayden Thring over 6 years
    Then just jump in ssh and tail the log
  • Vickar
    Vickar almost 6 years
    Very sophisticated one. Thanks @Pankaj Bisht
  • Metafaniel
    Metafaniel over 5 years
    Hi. Is there a newest fork or similar tool more up to date and currently maintained?
  • Mawg says reinstate Monica
    Mawg says reinstate Monica over 5 years
    I didn't code it, so for the newest fork, I guess just go to GitHub? For alternatives, ask at softwarerecs.stackexchange.com and we will help you.
  • Metafaniel
    Metafaniel over 5 years
    @MawgHi, thanks. I asked because phptoolcase Github and the forks listed there haven't been updated in 5 years. Thanks for the other StackExchange site. I just found Clockwork. I wonder if it's similar or better...
  • Mawg says reinstate Monica
    Mawg says reinstate Monica over 5 years
    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)
  • Steven Serrano
    Steven Serrano over 5 years
    @Magne Nothing. The moment that echo is read all header() calls will fail. This answer is not suited for those types of scenarios.
  • Olu Adabonyan
    Olu Adabonyan over 5 years
    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.
  • Dawson Irvine
    Dawson Irvine over 5 years
    @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?"
  • Cave Johnson
    Cave Johnson over 5 years
    I don't understand why you even need a div. if you just have a <script> block, nothing will be displayed in the browser.
  • SherylHohman
    SherylHohman about 5 years
    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 "<script>console.log(".json_encode($msg).")</script>";
  • SherylHohman
    SherylHohman about 5 years
    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 "<script>console.log(".json_encode($msg).")</script>";). 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.
  • Mbotet
    Mbotet about 5 years
    with this you can avoid var_dumps and similar. Works great and the console lets you toggle the json in a nice way.
  • Peter Mortensen
    Peter Mortensen almost 5 years
    Yes, but repeated code (redundancy) - ought to be refactored: $output = '<script>console.log("' . str_repeat(" ", $priority-1) and . '");</script>';. Only implode(",", $data) and $data is different.
  • Peter Mortensen
    Peter Mortensen almost 5 years
    An explanation would be in order.
  • Peter Mortensen
    Peter Mortensen almost 5 years
    What do you mean by "There not have a solid return or excessive usage of header().". Homonym error? It seems incomprehensible.
  • Peter Mortensen
    Peter Mortensen almost 5 years
    An explanation would be in order. Can you elaborate (by editing your answer, not by answering in comments)?
  • Peter Mortensen
    Peter Mortensen almost 5 years
  • zee
    zee almost 5 years
    @Peter Mortensen - true story! Edited this over 4yo post! :)
  • bueltge
    bueltge almost 5 years
    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.
  • Raphael Aleixo
    Raphael Aleixo over 4 years
    This snippet saved me. :) I needed to make some changes in production code without access to the actual servers, and this was perfect to get around it. Thanks!
  • HynekS
    HynekS over 4 years
    I am glad I was able to help.
  • user3445853
    user3445853 almost 4 years
    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.
  • JayJay123
    JayJay123 over 3 years
    This is sliced bread. Easy to implement, use,. and remove--at least in Chrome.
  • rmirabelle
    rmirabelle over 3 years
    Been using for years. Appears now fully dead. Link is 404. :-(
  • Erhan Demirci
    Erhan Demirci over 3 years
    thank worked well echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
  • David B
    David B over 3 years
    I got an 'Array' output, fixed with echo("<script>console.log('PHP OUTPUT: " . json_encode($data) . "');</script>");
  • Chiwda
    Chiwda over 2 years
    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.
  • bueltge
    bueltge over 2 years
    Yes, you have right. It is more in case of meta language, Info - information and log - logging, details behind in this thread are helpful. stackoverflow.com/questions/25532778/…
  • Duc Nguyen
    Duc Nguyen about 2 years
    echo "<script>console.log('Debug Objects: " . addslashes($output) . "' );</script>"; to fix in case single quote in the property value of object