11

As you know var_dump() in addition to value show its data type and length.

Is there any way to log its output to FireBug console?

I tried FirePHP and FireLogger but both output only value of a variable (sometimes even incorrect variable value).

Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • have you tried any Debugger ? like xdebug ? – Sujit Singh Feb 21 '13 at 05:38
  • @SujitSingh I want the output be shown on console, when you are developing an MVC application you can not see output of xdebug when it is called from controllers or models. – Handsome Nerd Feb 21 '13 at 05:40
  • @PHPst Are you using a framework or something? – j0k Mar 03 '13 at 15:12
  • @j0k I use Phalcon framework. But the question is in general – Handsome Nerd Mar 03 '13 at 15:30
  • 3
    For me, it's kind of "putting stuff inside what they can't belong". Firebug aims to handle what happens on the client side: css, html, js, event, xhr, etc.. not on the server side. Usually good framework, give ability to see what going on on their side when it builds the page. Symfony, Django, ZF, etc .. have a web debug toolbar for that. It's kind of *the firebug for server side*. What I recommend you to do instead of have a one place to see the rendering and the server side debugging, it too put `var_dump()` (maybe `var_export(..., true)` could be better) inside a log file and tail this file – j0k Mar 03 '13 at 16:04
  • if it is a string, console.log(string) and if it is an array, how about json_encode($variable) first – Youn Elan Mar 03 '13 at 19:32
  • 2
    I think you should be more concrete why FirePHP or FireLogger doesn't do the job for you because those two tools are exactly for that case. – hakre Mar 07 '13 at 16:48
  • do you need it to be IN THE CONSOLE ? any any place that you can see it using firebug ? – Abu Romaïssae Mar 09 '13 at 20:14
  • Thank you for the bounty. In case anything needs to be fixed or enhanced, just let me know. To answer other people's questions about FirePHP and FireLogger: apart from needing an extra plugin that may break with the next version of Firefox, both need output buffering, because they communicate through HTTP headers. Leaving output buffering enabled can cause bad surprises (and sadly often not immediately) once you disable it. – Walter Tross Mar 10 '13 at 21:01

12 Answers12

16

Maybe what you need is something like this:

function var2console($var, $name='', $now=false)
{
   if ($var === null)          $type = 'NULL';
   else if (is_bool    ($var)) $type = 'BOOL';
   else if (is_string  ($var)) $type = 'STRING['.strlen($var).']';
   else if (is_int     ($var)) $type = 'INT';
   else if (is_float   ($var)) $type = 'FLOAT';
   else if (is_array   ($var)) $type = 'ARRAY['.count($var).']';
   else if (is_object  ($var)) $type = 'OBJECT';
   else if (is_resource($var)) $type = 'RESOURCE';
   else                        $type = '???';
   if (strlen($name)) {
      str2console("$type $name = ".var_export($var, true).';', $now);
   } else {
      str2console("$type = "      .var_export($var, true).';', $now);
   }
}

function str2console($str, $now=false)
{
   if ($now) {
      echo "<script type='text/javascript'>\n";
      echo "//<![CDATA[\n";
      echo "console.log(", json_encode($str), ");\n";
      echo "//]]>\n";
      echo "</script>";
   } else {
      register_shutdown_function('str2console', $str, true);
   }
}

Usage: var2console($myvar, '$myvar'); or simply var2console($myvar);

It should very rarely be necessary to set the $now parameter to true, causing the immediate output of the <script> tag. The advantage of using register_shutdown_function() is that you don't need to pay attention to "where you are" in the HTML.

The json_encode() preserves all characters in the transfer from PHP to JavaScript. The only caveat is about encoding: json_encode() only works with UTF-8 (which is the recommended encoding in most cases, anyway). You may need something like utf8_encode() or mb_convert_encoding() if you use a different encoding (or rather, you may consider switching to UTF-8).

The output to Firebug's console is simply the output of var_export(), preceded by the type of the variable, including the length of strings and the count of arrays, and, optionally, by the name of the variable.

var_export() provides a more readable output than var_dump(). If you really need the output of var_dump(), you can use something like this:

function dump2console($var, $name='', $now=false)
{
   ob_start();
   if (strlen($name)) {
      echo "$name =\n";
   }
   var_dump($var);
   $str = ob_get_clean();
   str2console($str, $now);
}

Usage: dump2console($myvar, '$myvar'); or simply dump2console($myvar);

You should avoid circular references (var_dump() detects them a step too late, and var_export() doesn't detect them at all). This is how to do it, e.g., for $GLOBALS:

function globals2console($now=false)
{
   $g = $GLOBALS;
   $g['GLOBALS'] = '(recursion)';
   var2console($g, '$GLOBALS', $now);
}
Walter Tross
  • 12,237
  • 2
  • 40
  • 64
  • Why did you not use [`gettype()`](http://php.net/manual/en/function.gettype.php) for determining variable type easily? – Handsome Nerd Mar 12 '13 at 19:44
  • 1
    @PHPst only in order to be fully in control. I prefer bool over boolean, float over double (and, who knows, maybe you prefer int over integer) - and furthermore I already need the `if`s in order to add the length of strings and the count of arrays. – Walter Tross Mar 13 '13 at 07:55
15

You can dump JavaScript to the console by putting a console.log() in a script tag:

<script type="text/javascript">
console.log("hello");
</script>

So if you do a php dump in there...

<script type="text/javascript">
console.log("<?php var_dump('abc'); ?>");
</script>

You just need to be careful about ' and " in the var_dump breaking your JavaScript. In this example it will be ok because the HTML would be:

<script type="text/javascript">
console.log("string 'abc' (length=3)");
</script>

Just remember the php is processed then put in the JavaScript. You could also dump it to a comment:

<!--
<?php 
var_dump('abc');
?>
-->

Then you can view source, or inspect element.

Mark
  • 239
  • 1
  • 10
  • This is not practical in MVC – Handsome Nerd Mar 04 '13 at 17:57
  • 1
    Then another good question might be how to make this practical in MVC. This is fine for testing and getting values but if you want to use it in production you should probably look at covering your php to json so you can handle it properly in JavaScript. – Mark Mar 05 '13 at 06:23
  • I will upvote your answer. The exact to what I was going to write. – Keval Domadia Mar 05 '13 at 11:11
  • 1
    in my PHP var_dump('abc') is `string(3) "abc"`, which already breaks the code, but any array will break it too, because of the newlines. – Walter Tross Mar 10 '13 at 01:45
5
<script>console.log( <?= json_encode( $var ) ?> )</script>

Just throwing my hat in the ring. It sounds like FirePHP is the best way to go.

Collin James
  • 9,062
  • 2
  • 28
  • 36
4

FirePHP does the job well + you can use it while you're developing Ajax.

Sample code:

require_once('FirePHPCore/fb.php'); # add the library

fb($var); #log the variable
fb( var_export($var,true) ); # log the variable with the var_export format

If you're passing an array to it, you can click it from your console and it will open a popup on your screen. You can even expand/collapse arrays and objects.

EDIT: If you're looking for data types and length, use var_dump().

fb( var_dump( array(
    1,
    'a',
    true
  ) ) );
RRikesh
  • 14,112
  • 5
  • 49
  • 70
  • Did you test your answer before posting it? fb( var_export($var,true) ); only echoes value! – Handsome Nerd Feb 21 '13 at 09:25
  • Yes, it echoes the value in the browser console. if you want it to be clickable and pop up, you should pass it as an array `fb( array( var_export($var,true) ), 'TEST TITLE' );` – RRikesh Feb 21 '13 at 09:39
  • Outputs of `fb($var);`and `fb( var_export($var,true) );` are identical for me. – Handsome Nerd Mar 10 '13 at 14:10
2

I always use this script in combination with Zend_Log_Writer_Firebug (using firephp http://www.firephp.org/), because after redirects in the applicaton or ajax requests debugging with xdebug does not always work as expected:

require_once '/Zend/Log.php';
require_once '/Zend/Log/Writer/Firebug.php';  
require_once '/Zend/Controller/Response/Http.php';
require_once '/Zend/Controller/Request/Http.php';

// create the logger and log writer
$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);

// get the wildfire channel
$channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();

// create and set the HTTP response
$response = new Zend_Controller_Response_Http();
$channel->setResponse($response);

// create and set the HTTP request
$channel->setRequest(new Zend_Controller_Request_Http());

// record log messages
$logger->info('test');
$logger->info(var_export($_SESSION,true));
$logger->info(count(var_export($_SESSION,true)));
$logger->info(strlen(var_export('hello',true)));
$logger->info(get_type($_SESSION,true));  

// insert the wildfire headers into the HTTP response
$channel->flush();

// send the HTTP response headers
$response->sendHeaders();

You can build your own library to get the type of a variable:

<?php
function get_type($var) 
{
    if(is_object($var))
        return get_class($var);
    if(is_null($var))
        return 'null';
    if(is_string($var))
        return 'string';
    if(is_array($var))
        return 'array';
    if(is_int($var))
        return 'integer';
    if(is_bool($var))
        return 'boolean';
    if(is_float($var))
        return 'float';
    if(is_resource($var))
        return 'resource';
    //throw new NotImplementedException();
    return 'unknown';
}
?>

Using a function call to var_dump_ret as argument for $logger->info() might be helpful, too. I haven't tested it yet.

function var_dump_ret($mixed = null) {
  ob_start();
  var_dump($mixed);
  $content = ob_get_contents();
  ob_end_clean();
  return $content;
}
chris
  • 1,245
  • 1
  • 10
  • 22
  • Thanks, Why did you not use gettype() for determining type of a variable easily? – Handsome Nerd Mar 13 '13 at 08:51
  • There is a warning on the german gettype php documentation page: http://php.net/manual/de/function.gettype.php - Translated "for performance reasons" ;-). – chris Mar 13 '13 at 09:33
  • get_type() is a user defined function - gettype() is a php function. The underscore is important. – chris Apr 18 '13 at 09:42
2

if you just want to see the var_dump out put in the firebug (client side) without doing any things in Javascript I would recommande using cookies following is an illustration how you can perform it that way:

<?php
$str =  "Abu Romaïssae";

sendVarDumpToFront($str);

echo "<pre>";
echo $str."\n";

function sendVarDumpToFront( $mixed ){
    ob_start();
    var_dump($mixed);
    $content = ob_get_contents();
    ob_end_clean();
    setcookie("var_dump",$content);
}

than you can have it in firebug this way:

reading cookie content from Firebug

IMPORTANT

since this way uses cookies you will have to put the var_dump content before outputing any content otherwise this will not work

Abu Romaïssae
  • 3,841
  • 5
  • 37
  • 59
1

From: http://sixrevisions.com/web-development/how-to-debug-php-using-firefox-with-firephp/ Fb::log($array, "dumping an array") That will get you the type and data. You'll have to do extra logging manually for length/count.

Matt
  • 5,315
  • 1
  • 30
  • 57
1

The following will take anything from var_dump() and encode it in JSON before attempting to send it to console.log(). This prevents and special characters from messing up the output.

<?php
$myArray = array('Red','Green','Blue','Orange','Yellow','Purple');

ob_start();
var_dump($myArray);
$var_dump = ob_get_contents();
ob_end_clean();
?>

<script>
var var_dump = <?php echo json_encode($var_dump); ?>;
console.log(var_dump);
</script>
Jordan Mack
  • 8,223
  • 7
  • 30
  • 29
1

If you have an Ajax (XHR) call that is generating output with a var_dump() then you can inspect the request in FireBug either under 'Console' or 'Net'. Click the plus sign to expand it and look at the 'Response' tab.

Otherwise if you are putting var_dump() into the main page you are viewing it should just appear in the page as viewed although the formatting might be messed up. Try

echo '<PRE>' 

before the var_dump() or alternatively view the page source rather than the direct output.

Octopus
  • 8,075
  • 5
  • 46
  • 66
1

I think one easy way to achieve this goal is to do a simple

console.log(<?php var_export($var, true) ?>);

Alexandre GUIDET
  • 852
  • 9
  • 27
1

You are over complicating what is a simple issue. Firebug (and any other console/dom log viewer is for viewing client side output. PHP being server side and doesn't make much sense pushing to the console log.

With that said, if you REALLY wanted to pipe a server-side output to the console log you should convert that output into json and pass it onto the console log. If you simply want to output variable values on a life site without people knowing that you are working on it (and you shouldn't be working on a live version anyway but that's beside the point) why not pipe the output to a file and read that output however you like, you could even use ajax to pass the dump off to the log via jquery.

The point I am trying to make is...you are over-complicating what you are trying to do.

Hydra IO
  • 1,537
  • 1
  • 13
  • 28
-1

only from JavaScript a jquery From arrays in firebug and chrome is:

 console.dir('[object arrays]'); 

open the console and activate to F12... and write this code in console is the var_dump to php from jquery. array to json

var test = {"names":["john doe","JANE doe"],"ids":["123",null]}; console.dir(test);

if you need directly console fron PHP need a plugin