Better way to output PHP objects to console? - php

I'm trying to find the best way to debug PHP in the browser.
EDIT:
I know about xdebug, var_dump and print_r; that's not the point. a) I want a way to debug when a site is live (I know, that's bad but sometimes have to for a quick fix), b) dumping PHP variables all over a web page is ugly, and c) I sometimes need to know why AJAX calls aren't working, and it's easier to look at JSON in the console.
Possible other solutions include wrapping your debug output in a hidden div, e.g.
<div id="debug"><?php var_dump($all_the_junk) ?></div><script>document.getElementById('debug').style.display='none'</script>
and then typing something like
document.getElementById('debug')style.display = 'block'
into the console.
But let's be honest, that kind of sucks, and defeats the purpose of being able to see everything in a tidy way.
ENDEDIT;
So, anyways, I have the following code:
function log_as_json($vars)
{
if(is_resource($vars)) {
return;
}
else {
if($vars)
{
$json = #json_encode($vars);
print "<script>console.log($json);</script>";
}
}
}
The problem is that once in a while I get these terrible recursions, but I'm not sure what the best way is to check for types that json_encode supports. Also I suspect there is a better way to do this. Advice would be appreciated. Thanks!

If you are really keen on debugging in the browser, I'd recommend Chrome Logger (formerly known as ChromePHP).

The best way is to use xdebug And an IDE that allows you to set breakpoints

I use print_r or var_dump - it is what they are designed for.
I suppose you could embed these calls in console.log - not sure how they would display though.

I know this is old but here is a way that works for me, just call the function when you need to..
function console_log( $data ){
echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
}

Related

How to print to server console, not to browser or browser console [duplicate]

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.
error_log(print_r($variable, TRUE));
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)
If you are on Linux:
file_put_contents('your_log_file', 'your_content');
or
error_log ('your_content', 3, 'your_log_file');
and then in console
tail -f your_log_file
This will show continuously the last line put in the file.
You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.
In PHP, you have 3 categories of debugging solutions:
Output to a webpage (see dBug library for a nicer view of things).
Write to a log file
In session debugging with xDebug
Learn to use those instead of trying to make PHP behave like whatever other language you are used to.
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:
<div> some html code ....
some link to test
</div>
dump $tpl like this:
<pre><?php var_dump($tpl); ?></pre>
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.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Good luck!
You can also write to a file like this:
$logFilePath = '../logs/debug.text';
ob_start();
// if you want to concatenate:
if (file_exists($logFilePath)) {
include($logFilePath);
}
// for timestamp
$currentTime = date(DATE_RSS);
// echo log statement(s) here
echo "\n\n$currentTime - [log statement here]";
$logFile = fopen($logFilePath, 'w');
fwrite($logFile, ob_get_contents());
fclose($logFile);
ob_end_flush();
Make sure the proper permissions are set so php can access and write to the file (775).
If you don't want to integrate a framework like Zend, then you can use the trigger_error method to log to the php error log.
Simply way is trigger_error:
trigger_error("My error");
but you can't put arrays or Objects therefore use
var_dump
You can use the php curl module to make calls to http://liveoutput.com/. This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents.
This a great tool for debugging & logging php: PHp Debugger & Logger
It works right out of the box with just 3 lines of code.
It can send messages to the js console for ajax debugging and can replace the error handler.
It also dumps information about variables like var_dump() and print_r(), but in a more readable format.
Very nice tool!
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)
I use cakephp so I use:
$this->log(YOUR_STRING_GOES_HERE, 'debug');
You can use:
<?php
echo '<script>console.log("debug log")</script>';
?>
You can use
<?php
{
AddLog("anypage.php","reason",ERR_ERROR);
}
?>
or if you want to print that statement in an log you can use
AddLog("anypage.php","string: ".$string,ERR_DEBUG_LOW);

How to use var_dump in joomla

My question might be little silly but please bear with me. I suppose var_dump should work anywhere in the code which calls its service but unfortunately i can't return anything if i use it in a controller, or model. ya it does work in the view/layout page.
I tried testing the following simple thing in one of my controller function and it returns nothing;
$foo = "bar";
var_dump($foo);
Please enlighten me!
I don't know Joomla, but in an MVC framework, the view expects data to come from the controller in a particular format, perhaps JSON or XML. When you call var_dump(), it will most likely mess up the syntax of this, so the application won't work. When you're debugging with this tool, you'll want to make use of the browser's console (Developer Tools or Firebug) to view what was returned. Go into the Network tab, select the URL of the controller, and then view the response data. There you'll see the output of var_dump().
For show a variable and pause the executing you have 3 options.
echo $variable;
print_r($variable);
var_dump($variable);
and you need to write die() after them to stop code and show your $variable.

To be like Codeigniter and get that view partial with vanilla PHP?

Just wondering if anyone can point me in the right track to imitating the following Codeigniter method with pure PHP:
$string = $this->load->view('myfile', $data, true); // where $data is an array of info to "fill in" the html on the page
I've started with trying to use fopen, but i can't quite seem to figure out the part of sending data to the file before making it the string variable that i want to eventually send to the "master template".
At current, I'm stumped. I've been looking over their _ci_load method which feeds the above code, but it dives into more CI libs and the whole point of this is to make the "easiest pur php" way. If anyone has any advice, tips, tutorial links, anything I can't already find with Google
When I need something to quickly return part of a template, I use this.
function view($file,$data) {
extract($data);
ob_start();
if (is_file($file)) {
include($file);
}
$return = ob_get_clean();
return $return;
}
You should make sure to secure the contents of $file. Otherwise, anyone can load any file they want and inject it with the data they want. I normally use this only when I'm defining $file by hand, nothing dynamic.
I would recommend you look into using the ob_start(), ob_get_contents(), and ob_end_clean() functions.

Using eval() and base64_decode() to obfuscate code - not working within a function?

In short, I'm building a self hosted application, and to create a basic level deterrent that'll stop those who have a small knowledge of development (i.e. my target market) from removing call backs, I've decided to use eval() and base64_decode() in order to obfuscate and execute a couple of lines of code - specifically those that deal with validating the users license key.
The problem I've run into however is that it seems that I can't run eval(base64_decode(..)); within a function.
For example, this works fine:
eval(base64_decode('c2Vzc2lvbl9uYW1lKCJfaW5zdCIpOyBzZXNzaW9uX3N0YXJ0KCk7ICRfU0VTU0lPTlsna2V5J10gPSB0cnVlOyBlY2hvICI8c2NyaXB0IHR5cGU9XCJ0ZXh0L2phdmFzY3JpcHRcIj53aW5kb3cubG9jYXRpb24gPSAnL2luc3QvYWRtaW4vc2V0dGluZ3MnPC9zY3JpcHQ+Ijs=');
executing the following,
session_name("_inst");
session_start();
$_SESSION['key'] = true;
echo "<script type=\"text/javascript\">window.location = '/inst/admin/settings'</script>";
But this on the other hand, fails:
function escapeOut() {
eval(base64_decode('c2Vzc2lvbl9uYW1lKCJfaW5zdCIpOyBzZXNzaW9uX3N0YXJ0KCk7ICRfU0VTU0lPTlsna2V5J10gPSB0cnVlOyAkZXNjYXBlID0gICI8c2NyaXB0IHR5cGU9XCJ0ZXh0L2phdmFzY3JpcHRcIj53aW5kb3cubG9jYXRpb24gPSAnL2luc3QvYWRtaW4vc2V0dGluZ3MnPC9zY3JpcHQ+IjsgcmV0dXJuICRlc2NhcGU7'));
}
echo escapeOut();
it should execute the following,
session_name("_inst");
session_start();
$_SESSION['key'] = true;
$escape = "<script type=\"text/javascript\">window.location = '/inst/admin/settings'</script>";
return $escape;
At first I wasn't returning $escape, but after realizing and rectifying that issue, I'm stumped. It's probably something pretty simple, but I'm pretty stumped.
Any answers as to why this doesn't work/what I can do to make it work would be greatly appreciated!
having return in your eval() statement will return from eval, not from the outer function.
i think you need something like this:
function escapeOut(){
return eval(base64_decode('c2Vzc2lvbl9uYW1lKCJfaW5zdCIpOyBzZXNzaW9uX3N0YXJ0KCk7ICRfU0VTU0lPTlsna2V5J10gPSB0cnVlOyAkZXNjYXBlID0gICI8c2NyaXB0IHR5cGU9XCJ0ZXh0L2phdmFzY3JpcHRcIj53aW5kb3cubG9jYXRpb24gPSAnL2luc3QvYWRtaW4vc2V0dGluZ3MnPC9zY3JpcHQ+IjsgcmV0dXJuICRlc2NhcGU7'));
}
echo escapeOut();
also, keep in mind it's trivial to echo base64_decode('c2Vzc2lvbl9uYW1lKCJfaW5zdCIp...

What is another way of outputting data from an array rather than var_dump or print_r?

I'm on a 3rd party software and when I output the data from the array using var_dump() or print_r(), it comes out messy.
Anyone know of a way to output the data in a hierarchical format or something more organized (or some script that does it for me)?
Thanks!
If you mean messy, as in not formatted, you could use <pre> to get it to format it as it's printed.
Or write a function like so
function debug($debug) {
if (is_array($debug)) {
echo '<pre>' . print_r($debug, TRUE) . '</pre>';
} else {
echo $debug;
}
}
Use print_a() from debuglib! http://phpdebuglib.de this is what you want :-)
You can throw in any array and it gets dispalyed in a nice table, also nested data.
You can put it inside the page or at the end.
Take a look at http://kaloyan.info/krumo/
Except the collapsible DHTML tree built around the structure of the dumped PHP variable, and the improved by the CSS looks, Krumo offers additional useful features.
...or install a "real" debugger like e.g. xdebug combined with netbeans with the php plugin.

Categories