List all PHP variables

PhpVariablesGlobal Variables

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

Use get_defined_vars and/or get_defined_constants

$arr = get_defined_vars();
print_r($arr);

Solution 2 - Php

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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSalman AView Question on Stackoverflow
Solution 1 - PhpnicoView Answer on Stackoverflow
Solution 2 - PhpJohnView Answer on Stackoverflow