13 years ago

A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

Array
[ GLOBALS ] => Array
[ GLOBALS ] => Array
*RECURSION*
[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()
)

[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()

)
?>

Notice that $_SERVER isn't there. It seems that php only loads the superglobal $_SERVER if it is used somewhere. You could do this:

print "

" . htmlspecialchars(print_r(get_defined_vars(), true))."
" ;
print "
" . htmlspecialchars (print_r ($_SERVER , true )) . "
" ;
?>

And then $_SERVER will appear in both lists. I guess it"s not really a gotcha, because nothing bad will happen either way, but it"s an interesting curiosity nonetheless.

6 years ago

Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = "foo" ;
$bar = "bar" ;

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(), $vars);

echo "

"
;
print_r($vars);
echo "
" ;
?>

15 years ago

Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

function generateDebugReport ($method, $defined_vars, $email = "undefined" )(
// Function to create a debug report to display or email.
// Usage: generateDebugReport(method,get_defined_vars(),email);
// Where method is "browser" or "email".

// Create an ignore list for keys returned by "get_defined_vars".
// For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
// redundant (same as _POST, _GET)
// Also include vars you want ignored for security reasons - i.e. PHPSESSID.
$ignorelist =array("HTTP_POST_VARS" , "HTTP_GET_VARS" ,
"HTTP_COOKIE_VARS" , "HTTP_SERVER_VARS" ,
"HTTP_ENV_VARS" , "HTTP_SESSION_VARS" ,
"_ENV" , "PHPSESSID" , "SESS_DBUSER" ,
"SESS_DBPASS" , "HTTP_COOKIE" );

$timestamp = date ("m/d/y h:m:s" );
$message = "Debug report created $timestamp \n" ;

// Get the last SQL error for good measure, where $link is the resource identifier
// for mysql_connect. Comment out or modify for your database or abstraction setup.
global $link ;
$sql_error = mysql_error($link);
if($sql_error )(
$message .= "\nMysql Messages:\n" . mysql_error($link);
}
// End MySQL

// Could use a recursive function here. You get the idea ;-)
foreach($defined_vars as $key => $val )(
if(is_array ($val ) && ! in_array ($key , $ignorelist ) && count ($val ) > 0 )(
$message .= "\n $key array (key=value):\n" ;
foreach($val as $subkey => $subval )(
if(! in_array ($subkey , $ignorelist ) && ! is_array ($subval ))(
$message .= $subkey . " = " . $subval. "\n" ;
}
elseif(! in_array ($subkey, $ignorelist) && is_array ($subval ))(
foreach($subval as $subsubkey => $subsubval )(
if(! in_array ($subsubkey, $ignorelist))(
$message .= $subsubkey . " = " . $subsubval . "\n" ;
}
}
}
}
}
elseif(!
is_array ($val ) && ! in_array ($key , $ignorelist ) && $val )(
$message .= "\nVariable " . $key . " = " . $val. "\n" ;
}
}

If($method == "browser" )(
echo nl2br($message);
}
elseif($method == "email" )(
if($email == "undefined" )(
$email = $_SERVER [ "SERVER_ADMIN" ];
}

$mresult = mail ($email , "Debug Report for " . $_ENV [ "HOSTNAME" ]. "" , $message );
if($mresult == 1 )(
echo "Debug Report sent successfully.\n";
}
else(
echo "Failed to send Debug Report.\n";
}
}
}
?>

17 years ago

Simple routine to convert a get_defined_vars object to XML.

function obj2xml ($v, $indent = "" ) (
while (list($key , $val ) = each ($v )) (
if ($key == "__attr" ) continue;
// Check for __attr
if (is_object ($val -> __attr )) (
while (list($key2 , $val2 ) = each ($val -> __attr )) (
$attr .= " $key2 =\" $val2 \"" ;
}
}
else $attr = "" ;
if (is_array ($val ) || is_object ($val )) (
print(" $indent< $key$attr >\n" );
obj2xml($val, $indent. "");
print(" $indent\n" );
}
else print(" $indent< $key$attr >$val\n" );
}
}

//Example object
$x -> name -> first = "John" ;
$x -> name -> last = "Smith" ;
$x -> arr [ "Fruit" ] = "Bannana" ;
$x -> arr [ "Veg" ] = "Carrot" ;
$y -> customer = $x ;
$y -> customer -> __attr -> id = "176C4" ;

$z = get_defined_vars();
obj2xml($z["y"]);
?>
will output:


John
Smith


Banana
Carrot

11 years ago

As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

// define a variable
$my_var = "foo" ;

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars [ "my_var" ] = "bar" ;

echo $my_var , "\n" ;

?>

will output "foo" (the original value). It"d be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name)
{
$defined_vars [ $var_name ] =& $ $var_name ;
}

?>

1 year ago

I posted here before about "this" being in get_defined_vars.

It turns out it"s not always there but in certain cases it will inexplicably appear.

Php -r "
class Test(
public function a() (var_dump(array_keys(get_defined_vars()));$a = 123;)
public function b() (var_dump(array_keys(get_defined_vars()));$this;)
}
$t = new Test();
$t->a();
$t->b();
"

Array()
array("this")

This does not happen in PHP 7.2 but will happen in PHP 5.6.

1 year ago

Some comments here point out that this function wont return references. It does however return names and names are "references".

I would not recommend the suggestions here that convert it to references.

Public function x($a, $b, $c) (
foreach(array_keys(get_defined_vars()) as $key)
if($key !== "this")
$this->y($($key));
}

Public function y(&$input) (
$input++;
}

Instead of $() you can also use $$.

I have done some whacky things in my time to make extremely generic code but I"ve never had to do anything like the above. It might not even work (but should since it"s no different to $a[$key]).

You could also do $$key++ but I"ve never seen code like that which wasn"t horrifically bad (using dynamic where dynamic isn"t beneficial).

If you"re doing something like that then give it additional scrutiny.

Surely you have a closet or chest of drawers at home. The principle of their use is simple: we put things there that we don’t need right now, but may need in a while.

The variables are arranged exactly the same. You can put some value in them and store it there until you need it.

Creating Variables

You can put a value in a variable like this:

In the code above, we created a variable $name and put the value Ivan in it, then we created a variable $age and assigned it the value 20.

The name "variable" means that its value can change during script execution:

In some languages, a variable must first be “declared” and then used. There is no declaration in PHP - a variable is created the moment you put a value into it.
However, PHP programmers often say "declare a variable" instead of "create a variable".

Also, instead of “put a value into a variable,” they often say “assign a value.”
The reason is simple - the = symbol, thanks to which we store a value in a variable, is called the “assignment operator”. Hence the term "appropriate".

Variable naming rules

1. The variable name begins with the $ symbol.

2. The second character can be a letter or an underscore _

Variable names are case sensitive. $name and $Name are different variables.

Displaying the value of a variable on the screen

You can display a variable using the echo command we already know:

The echo command allows you to display multiple values ​​at once:

Notice that we passed 2 values ​​to echo, separated by a comma. This way we can pass as many values ​​as we want. The following two examples will produce the same result:

There is also a shorthand syntax for displaying variables in PHP. Instead of

Prior to PHP 5.4, the shorthand syntax only worked if the short_open_tag directive was enabled in the PHP settings, which also allows the use of a shortened opening tag

Checking the value of a variable

The echo command is not always convenient for checking the current value of a variable. For example, if you try to display the empty string "", absolutely nothing will be displayed on the screen. And it is not clear what the reason is - an empty variable or broken code.

Therefore, to check the value of a variable, the var_dump() function is used:

Result of script execution:

String(5) "Vasya" string(0) ""

As you can see, PHP displayed not only the contents of the variable, but also the number of characters, and even the type of the variable (string). We will look at data types in detail in the following lessons.

Removing Variables

You can remove an existing variable using the unset() function:

Now it's time to practice a little.

Remember, almost any PHP problem can have multiple solutions. Therefore, if your solutions differ from those written on this site, this does not mean at all that you did something wrong.

Write a script that:
1. Creates variables with the names title and content and some values.
2. Displays the value of the title variable inside the h1 tag, and the value of the content variable inside the div tag.

Show solution

", $title, ""; echo "

", $content, "
"; ?>

I would like to once again draw your attention to the fact that this decision is not the only correct one. For example, the following code will produce the same result:

13 years ago

A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

Array
[ GLOBALS ] => Array
[ GLOBALS ] => Array
*RECURSION*
[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()
)

[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()

)
?>

Notice that $_SERVER isn't there. It seems that php only loads the superglobal $_SERVER if it is used somewhere. You could do this:

print "

" . htmlspecialchars(print_r(get_defined_vars(), true))."
" ;
print "
" . htmlspecialchars (print_r ($_SERVER , true )) . "
" ;
?>

And then $_SERVER will appear in both lists. I guess it"s not really a gotcha, because nothing bad will happen either way, but it"s an interesting curiosity nonetheless.

6 years ago

Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = "foo" ;
$bar = "bar" ;

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(), $vars);

echo "

"
;
print_r($vars);
echo "
" ;
?>

15 years ago

Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

function generateDebugReport ($method, $defined_vars, $email = "undefined" )(
// Function to create a debug report to display or email.
// Usage: generateDebugReport(method,get_defined_vars(),email);
// Where method is "browser" or "email".

// Create an ignore list for keys returned by "get_defined_vars".
// For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
// redundant (same as _POST, _GET)
// Also include vars you want ignored for security reasons - i.e. PHPSESSID.
$ignorelist =array("HTTP_POST_VARS" , "HTTP_GET_VARS" ,
"HTTP_COOKIE_VARS" , "HTTP_SERVER_VARS" ,
"HTTP_ENV_VARS" , "HTTP_SESSION_VARS" ,
"_ENV" , "PHPSESSID" , "SESS_DBUSER" ,
"SESS_DBPASS" , "HTTP_COOKIE" );

$timestamp = date ("m/d/y h:m:s" );
$message = "Debug report created $timestamp \n" ;

// Get the last SQL error for good measure, where $link is the resource identifier
// for mysql_connect. Comment out or modify for your database or abstraction setup.
global $link ;
$sql_error = mysql_error($link);
if($sql_error )(
$message .= "\nMysql Messages:\n" . mysql_error($link);
}
// End MySQL

// Could use a recursive function here. You get the idea ;-)
foreach($defined_vars as $key => $val )(
if(is_array ($val ) && ! in_array ($key , $ignorelist ) && count ($val ) > 0 )(
$message .= "\n $key array (key=value):\n" ;
foreach($val as $subkey => $subval )(
if(! in_array ($subkey , $ignorelist ) && ! is_array ($subval ))(
$message .= $subkey . " = " . $subval. "\n" ;
}
elseif(! in_array ($subkey, $ignorelist) && is_array ($subval ))(
foreach($subval as $subsubkey => $subsubval )(
if(! in_array ($subsubkey, $ignorelist))(
$message .= $subsubkey . " = " . $subsubval . "\n" ;
}
}
}
}
}
elseif(!
is_array ($val ) && ! in_array ($key , $ignorelist ) && $val )(
$message .= "\nVariable " . $key . " = " . $val. "\n" ;
}
}

If($method == "browser" )(
echo nl2br($message);
}
elseif($method == "email" )(
if($email == "undefined" )(
$email = $_SERVER [ "SERVER_ADMIN" ];
}

$mresult = mail ($email , "Debug Report for " . $_ENV [ "HOSTNAME" ]. "" , $message );
if($mresult == 1 )(
echo "Debug Report sent successfully.\n";
}
else(
echo "Failed to send Debug Report.\n";
}
}
}
?>

17 years ago

Simple routine to convert a get_defined_vars object to XML.

function obj2xml ($v, $indent = "" ) (
while (list($key , $val ) = each ($v )) (
if ($key == "__attr" ) continue;
// Check for __attr
if (is_object ($val -> __attr )) (
while (list($key2 , $val2 ) = each ($val -> __attr )) (
$attr .= " $key2 =\" $val2 \"" ;
}
}
else $attr = "" ;
if (is_array ($val ) || is_object ($val )) (
print(" $indent< $key$attr >\n" );
obj2xml($val, $indent. "");
print(" $indent\n" );
}
else print(" $indent< $key$attr >$val\n" );
}
}

//Example object
$x -> name -> first = "John" ;
$x -> name -> last = "Smith" ;
$x -> arr [ "Fruit" ] = "Bannana" ;
$x -> arr [ "Veg" ] = "Carrot" ;
$y -> customer = $x ;
$y -> customer -> __attr -> id = "176C4" ;

$z = get_defined_vars();
obj2xml($z["y"]);
?>
will output:


John
Smith


Banana
Carrot

11 years ago

As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

// define a variable
$my_var = "foo" ;

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars [ "my_var" ] = "bar" ;

echo $my_var , "\n" ;

?>

will output "foo" (the original value). It"d be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name)
{
$defined_vars [ $var_name ] =& $ $var_name ;
}

?>

1 year ago

I posted here before about "this" being in get_defined_vars.

It turns out it"s not always there but in certain cases it will inexplicably appear.

Php -r "
class Test(
public function a() (var_dump(array_keys(get_defined_vars()));$a = 123;)
public function b() (var_dump(array_keys(get_defined_vars()));$this;)
}
$t = new Test();
$t->a();
$t->b();
"

Array()
array("this")

This does not happen in PHP 7.2 but will happen in PHP 5.6.

1 year ago

Some comments here point out that this function wont return references. It does however return names and names are "references".

I would not recommend the suggestions here that convert it to references.

Public function x($a, $b, $c) (
foreach(array_keys(get_defined_vars()) as $key)
if($key !== "this")
$this->y($($key));
}

Public function y(&$input) (
$input++;
}

Instead of $() you can also use $$.

I have done some whacky things in my time to make extremely generic code but I"ve never had to do anything like the above. It might not even work (but should since it"s no different to $a[$key]).

You could also do $$key++ but I"ve never seen code like that which wasn"t horrifically bad (using dynamic where dynamic isn"t beneficial).

If you"re doing something like that then give it additional scrutiny.

Environment variables in Windows contain various information about system settings and the user's environment. A distinction is made between user, system and process environment variables.

The easiest way to view the contents of environment variables in Windows is to open System Properties ( sysdm.cpl) -> Advanced -> Environment Variables. As you can see, in the window that opens there are two sections: the upper one contains the user’s environment variables, and the lower one contains the system ones.

In addition, environment variables are stored in the system registry. User variables are stored in the . System - in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

You can display the values ​​of all environment variables in the command line Windows line. The command is simple:

The command will output a list environment variables and their meanings.

In PowerShell, you can use the command to display all environment variables:

If you need to display the value of only one variable, you need to use the echo command, and the variable name must be enclosed in percent signs. For example,

Echo %systemroot%

set > c:\tmp\env_var.txt

Environment variables for a specific process can be obtained using the free Process Explorer utilities(from Sysinternals). Just open the process properties and go to the tab Environment.