I'd like to debug some PHP code, but I guess printing a log to screen or file is fine for me.
How should I print a log in PHP code?
The usual print
/printf
seems to go to HTML output not the console.
I have Apache server executing the PHP code.
I'd like to debug some PHP code, but I guess printing a log to screen or file is fine for me.
How should I print a log in PHP code?
The usual print
/printf
seems to go to HTML output not the console.
I have Apache server executing the PHP code.
A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so
file_put_contents('php://stderr', print_r($foo, TRUE))
will nicely dump the value of$foo
into the Apache error log.I use cakephp so I use:
Are you debugging on console? There are various options for debugging PHP. The most common function used for quick & dirty debugging is var_dump.
That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.
Things to help out if debugging in a webpage, wrap
<pre> </pre>
tags around your dump statement to give you proper formatting on arrays and objects.Ie:
And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.
Good luck!
might be useful
You can use error_log to send to your servers error log file (or an optional other file if you'd like)
I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see http://www.codeforest.net/debugging-php-in-browsers-javascript-console).
That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.
Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.
If anyone does decide to us that code, I made one minor change. After
function debug($name, $var = null, $type = LOG) {
I added
$name = 'PHP: ' . $name;
This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.
(Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)