64

Is it possible to dump all global variables in a PHP script? Say this is my code:

<?php
$foo = 1;
$bar = "2";
include("blah.php");
dumpall();
// displays $foo, $bar and all variables created by blah.php

Also, is it possible to dump all defined constants in a PHP script.

Salman A
  • 262,204
  • 82
  • 430
  • 521

2 Answers2

107

Use get_defined_vars and/or get_defined_constants

$arr = get_defined_vars();
print_r($arr);
nico
  • 50,859
  • 17
  • 87
  • 112
14

When debugging trying to find differences using a program such as WinMerge (freeware) to see what differences various arrays and variables have you'll want to ksort() otherwise you'll get lots of false negatives. It also helps to visually format using the HTML pre element...

<?php
$everything = get_defined_vars();
ksort($everything);

?>

Edit: had to come back to this and realized I had a better answer, $GLOBALS.

$a = print_r(var_dump($GLOBALS),1);
echo '<pre>';
echo htmlspecialchars($a);
echo '</pre>';

Edit 2: as mpag mentioned print_r() may be susceptible to running out of memory if the software you're working with uses a lot. Presuming there is no output or it's clearly truncated and you have access to the php.ini file you can adjust the memory use as so:

ini_set('memory_limit', '1024M');
John
  • 1
  • 13
  • 98
  • 177
  • 1
    This answer is gold for me. – quantme Nov 12 '15 at 16:28
  • 1
    three comments: 1) `print_r` runs out of memory when using a class-heavy CMS, but `json_encode($GLOBALS)` with `console.log`ging javascript works. 2) Don't forget the $_ variables (SERVER, SESSION, ENV, FILES, COOKIE, GET, POST, REQUEST). 3) for more in-depth debugging i also do a `get_declared_classes` and iterate though those to `get_class_vars` and `get_class_methods` – mpag Jun 14 '18 at 17:48
  • @mpag Ah yes, I've seen some software use ludicrous amounts of memory; apparently the work around for that is to obviously either not use such a system but a lot of folks won't have that option so https://stackoverflow.com/a/16423653/606371 will hopefully work for them. Also if I recall correctly the `$_` variables should be pulled from `$GLOBALS`. Thanks for your comment, I'll look in to `get_declared_classes` and `get_class_vars` soon. :-) – John Jun 14 '18 at 19:29
  • I'm already setting my limit to 512M, and I believe it's unlikely that doubling to 1024 will resolve this issue in my case. I believe 2048M is the hard limit for php. – mpag Jun 14 '18 at 21:04