How can I write to the console in PHP?
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.
- Chrome - Xdebug Helper
- Firefox - The easiest Xdebug
- Opera - Xdebug
- Safari - Xdebug Toggler
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>");
![Labeeb Panampullan](https://i.stack.imgur.com/STf0R.jpg?s=256&g=1)
Labeeb Panampullan
Updated on January 04, 2022Comments
-
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 over 11 yearsThere's also a Safari extension for debugging PHP called Xdebug Helper. I installed it from this page: extensions.apple.com/#tab
-
barbushin over 10 yearsI think the best debugging extension for Google Chrome is PHP Console chrome.google.com/webstore/detail/php-console/…
-
Martín Coll over 10 yearsThanks,
error_log
is what I needed to output to the terminal from the PHP built-in web server -
Miro Markaravanes over 10 yearsThis 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 over 10 yearsIn FireFox v27 it outputs
"Debug Objects: " . $data . ""
-
dsimer about 10 yearsNothing for Internet Explorer? I realize it's not number one, but it's still up there...
-
Imperative almost 10 yearsThe only way to make this more useful would be to do a variable $name : 'data' pair in the log. Nice function though.
-
tony gil over 9 yearsperfect solution. just swap
console.log
FORalert
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 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 todebug_to_console
. The browser should never see$data
. (If you look atpage source
in browser, it should not say$data
.) -
Magne almost 9 yearsWhat do you do with the resulting "Cannot modify header information -" errors?
-
Paolo almost 9 yearsIf 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 almost 9 yearsDoesn't work at all with debugging JSON requests, as it adds markup to the response
-
Brian Leishman almost 9 yearsFire PHP link is dead
-
mmv_sat almost 9 yearsUseful but doesn't work in its current form for an associated array. Or as someone mentioned a JSON request.
-
Velojet almost 9 yearsMy 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 about 8 yearsso 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 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 about 8 yearsYou should add a hint about your idea and solution. Also the source have unused source.
-
bueltge about 8 yearsThanks for the hint to my post. But the time and the knowledge has changed, the function also ;) I have it update now.
-
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 almost 8 yearsWhile I do like this idea, could you confirm that it would not be suitable for Ajax requests?
-
bueltge almost 8 yearsYes, it is pure static php, not Ajax.
-
Mawg says reinstate Monica almost 8 yearsBut, 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 almost 8 yearsYou should trigger the helper function before request the ajax call, then you get also a result in the console.
-
Azmat Karim Khan almost 8 yearsecho "<script> console.log('PHP: ',",get_option("slides_data"),");</script>";
-
whoshotdk almost 8 yearsI'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 over 7 yearsSo 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 over 7 yearsSo it seems it did the \n after each char when I passed a numeric value and not a string I think.
-
bueltge over 7 yearsThat's a formatting point of the console, not from the helper function.
-
padawanTony over 7 yearsYou can also install it via composer:
"ccampbell/chromephp": "*"
-
robrecord over 7 yearsThis 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 over 7 yearsOP states he wanted to print to standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to server-side terminal / standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to server-side terminal / standard output, not to html/js console.
-
beppe9000 over 7 yearsOP states he wanted to print to server-side terminal / standard output, not to html/js console.
-
zee over 7 years@beppe9000, not really. You edited the OPs question changing it completely. stackoverflow.com/posts/4323411/revisions
-
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 over 7 yearsFirePHP is officially dead.
-
Christine almost 7 yearsSo, in other words, the answer is this: echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
-
Rolf over 6 yearsTechnically 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 over 6 yearsi certainly just found it incredibly helpful!
-
Hayden Thring over 6 yearsThen just jump in ssh and tail the log
-
Vickar almost 6 yearsVery sophisticated one. Thanks @Pankaj Bisht
-
Metafaniel over 5 yearsHi. Is there a newest fork or similar tool more up to date and currently maintained?
-
Mawg says reinstate Monica over 5 yearsI 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 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 over 5 yearsAnd 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 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 over 5 yearsKeeping 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 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 over 5 yearsI don't understand why you even need a
div
. if you just have a<script>
block, nothing will be displayed in the browser. -
SherylHohman about 5 yearsAlso, 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 about 5 yearsWould 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 causedconsole.log
or xml output to break. In many cases, an error log as you did is much better than a quickconsole.log
. -
Mbotet about 5 yearswith this you can avoid var_dumps and similar. Works great and the console lets you toggle the json in a nice way.
-
Peter Mortensen almost 5 yearsYes, but repeated code (redundancy) - ought to be refactored:
$output = '<script>console.log("' . str_repeat(" ", $priority-1)
and. '");</script>';
. Onlyimplode(",", $data)
and$data
is different. -
Peter Mortensen almost 5 yearsAn explanation would be in order.
-
Peter Mortensen almost 5 yearsWhat do you mean by "There not have a solid return or excessive usage of
header()
.". Homonym error? It seems incomprehensible. -
Peter Mortensen almost 5 yearsAn explanation would be in order. Can you elaborate (by editing your answer, not by answering in comments)?
-
Peter Mortensen almost 5 years
-
zee almost 5 years@Peter Mortensen - true story! Edited this over 4yo post! :)
-
bueltge almost 5 yearsI 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 over 4 yearsThis 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 over 4 yearsI am glad I was able to help.
-
user3445853 almost 4 yearsAt 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 withget_transient( ... )
then add some content at the end. -
JayJay123 over 3 yearsThis is sliced bread. Easy to implement, use,. and remove--at least in Chrome.
-
rmirabelle over 3 yearsBeen using for years. Appears now fully dead. Link is 404. :-(
-
Erhan Demirci over 3 yearsthank worked well echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
-
David B over 3 yearsI got an 'Array' output, fixed with
echo("<script>console.log('PHP OUTPUT: " . json_encode($data) . "');</script>");
-
Chiwda over 2 yearsWhy 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 over 2 yearsYes, 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 about 2 yearsecho "<script>console.log('Debug Objects: " . addslashes($output) . "' );</script>"; to fix in case single quote in the property value of object