Variables in PHP. Variables in PHP Php dump all post variables

Environment variables (environment) in Windows contain various information about the system settings and the user's environment. Distinguish 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) -\u003e Advanced -\u003e Environment Variables. As you can see, in the opened section there are two sections: the upper one contains the user's environment variables, the lower one contains the system ones.

Additionally, environment variables are stored in the system registry. Custom variables are stored in the section. System - in HKLM \\ SYSTEM \\ CurrentControlSet \\ Control \\ Session Manager \\ Environment.

You can display the values \u200b\u200bof all environment variables in the Windows command line. The command is simple:

The command will list the environment variables and their values.

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

If you want 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\u003e c: \\ tmp \\ env_var.txt

Environment variables of a specific process can be obtained using the free process Explorer utilities (from Sysinternals). It is enough to open the properties of the process and go to the tab Environment.

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] \u003d\u003e Array
[GLOBALS] \u003d\u003e Array
* RECURSION *
[_POST] \u003d\u003e Array ()
[_GET] \u003d\u003e Array ()
[_COOKIE] \u003d\u003e Array ()
[_FILES] \u003d\u003e Array ()
)

[_POST] \u003d\u003e Array ()
[_GET] \u003d\u003e Array ()
[_COOKIE] \u003d\u003e Array ()
[_FILES] \u003d\u003e 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 \u003d get_defined_vars ();

// Now do your stuff
$ foo \u003d "foo";
$ bar \u003d "bar";

// Get all the variables defined in current scope
$ vars \u003d 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 \u003d "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 \u003d 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 \u003d date ("m / d / y h: m: s");
$ message \u003d "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 \u003d mysql_error ($ link);
if ($ sql_error) (
$ message. \u003d "\\ nMysql Messages: \\ n". mysql_error ($ link);
}
// End MySQL

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

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

$ mresult \u003d mail ($ email, "Debug Report for". $ _ENV ["HOSTNAME"]. "", $ message);
if ($ mresult \u003d\u003d 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 \u003d "") (
while (list ($ key, $ val) \u003d each ($ v)) (
if ($ key \u003d\u003d "__attr") continue;
// Check for __attr
if (is_object ($ val -\u003e __attr)) (
while (list ($ key2, $ val2) \u003d each ($ val -\u003e __attr)) (
$ attr. \u003d "$ key2 \u003d \\" $ val2 \\ "";
}
}
else $ attr \u003d "";
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 -\u003e name -\u003e first \u003d "John";
$ x -\u003e name -\u003e last \u003d "Smith";
$ x -\u003e arr ["Fruit"] \u003d "Bannana";
$ x -\u003e arr ["Veg"] \u003d "Carrot";
$ y -\u003e customer \u003d $ x;
$ y -\u003e customer -\u003e __attr -\u003e id \u003d "176C4";

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


John
Smith


Bannana
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 \u003d "foo";

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

// now try to change the value through the returned array
$ defined_vars ["my_var"] \u003d "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 \u003d array ();
$ var_names \u003d array_keys (get_defined_vars ());

foreach ($ var_names as $ var_name)
{
$ defined_vars [$ var_name] \u003d & $ $ 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 \u003d 123;)
public function b () (var_dump (array_keys (get_defined_vars ())); $ this;)
}
$ t \u003d new Test ();
$ t-\u003e a ();
$ t-\u003e 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! \u003d\u003d "this")
$ this-\u003e 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.

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] \u003d\u003e Array
[GLOBALS] \u003d\u003e Array
* RECURSION *
[_POST] \u003d\u003e Array ()
[_GET] \u003d\u003e Array ()
[_COOKIE] \u003d\u003e Array ()
[_FILES] \u003d\u003e Array ()
)

[_POST] \u003d\u003e Array ()
[_GET] \u003d\u003e Array ()
[_COOKIE] \u003d\u003e Array ()
[_FILES] \u003d\u003e 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 \u003d get_defined_vars ();

// Now do your stuff
$ foo \u003d "foo";
$ bar \u003d "bar";

// Get all the variables defined in current scope
$ vars \u003d 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 \u003d "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 \u003d 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 \u003d date ("m / d / y h: m: s");
$ message \u003d "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 \u003d mysql_error ($ link);
if ($ sql_error) (
$ message. \u003d "\\ nMysql Messages: \\ n". mysql_error ($ link);
}
// End MySQL

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

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

$ mresult \u003d mail ($ email, "Debug Report for". $ _ENV ["HOSTNAME"]. "", $ message);
if ($ mresult \u003d\u003d 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 \u003d "") (
while (list ($ key, $ val) \u003d each ($ v)) (
if ($ key \u003d\u003d "__attr") continue;
// Check for __attr
if (is_object ($ val -\u003e __attr)) (
while (list ($ key2, $ val2) \u003d each ($ val -\u003e __attr)) (
$ attr. \u003d "$ key2 \u003d \\" $ val2 \\ "";
}
}
else $ attr \u003d "";
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 -\u003e name -\u003e first \u003d "John";
$ x -\u003e name -\u003e last \u003d "Smith";
$ x -\u003e arr ["Fruit"] \u003d "Bannana";
$ x -\u003e arr ["Veg"] \u003d "Carrot";
$ y -\u003e customer \u003d $ x;
$ y -\u003e customer -\u003e __attr -\u003e id \u003d "176C4";

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


John
Smith


Bannana
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 \u003d "foo";

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

// now try to change the value through the returned array
$ defined_vars ["my_var"] \u003d "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 \u003d array ();
$ var_names \u003d array_keys (get_defined_vars ());

foreach ($ var_names as $ var_name)
{
$ defined_vars [$ var_name] \u003d & $ $ 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 \u003d 123;)
public function b () (var_dump (array_keys (get_defined_vars ())); $ this;)
}
$ t \u003d new Test ();
$ t-\u003e a ();
$ t-\u003e 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! \u003d\u003d "this")
$ this-\u003e 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 do not need right now, but may be needed after a while.

Variables work the same way. You can put some value in them and store there until you need it.

Creating Variables

You can put a value into a variable as follows:

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

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 variable" instead of "create variable".

Also, instead of "putting a value in a variable," they often say "assign a value".
The reason is simple - the \u003d symbol, thanks to which we store a value in a variable, is called an "assignment operator". Hence the term "appropriate".

Variable naming rules

1. Variable name starts with $ 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 the variable using the echo command we already know:

The echo command allows you to display multiple values \u200b\u200bat once:

Note that we passed 2 values \u200b\u200bto echo, separated by commas. So we can transfer as many values \u200b\u200bas we want. The following two examples will produce the same result:

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

Before PHP 5.4, the shorthand syntax only worked when the short_open_tag directive was enabled in the PHP settings, which also allows the use of the shorthand 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 an empty string, "" nothing will be displayed on the screen. And it is not clear what the reason is - an empty variable or non-working code.

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

The result of the 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 take a closer look at data types in the next lessons.

Deleting Variables

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

Now it's time to practice a little.

Remember, almost any PHP task can have multiple solutions. Therefore, if your decisions 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 titles title and content and some values.
2. Outputs 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 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:

This lesson explores the scope of PHP variables. Explains the difference between local and global scopes, shows how to access global variables within a function, how to work with superglobals, and how to create static variables.

When you start learning PHP and start working with functions and objects, the scope of variables is a bit confusing. Fortunately, PHP's rules in this regard are very easy to understand (compared to other programming languages).

What is scope?

Variable scope is the context within which a variable was defined and where it can be accessed. PHP has two variable scopes:

  • The global - variables can be accessed anywhere in the script
  • Local - variables can only be accessed inside the function in which they were defined

Variable scope, and especially local scope, greatly facilitates code management. If all the variables were global, then they could be changed anywhere in the script. This would lead to chaos and large scripts, since very often different parts of the script use variables with the same name. By scoping the local context, you define the boundaries of the code that can access the variable, making the code more robust, modular, and easier to debug.

Variables that are globally scoped are called global, and those that are locally scoped are called local.

Here's an example of how global and local variables work.

";) sayHello (); echo" Value \\ $ globalName: "$ globalName"
"; echo" Value \\ $ localName: "$ localName"
"; ?>

Hi Harry! $ GlobalName value: "Zoe" $ localName value: ""

In this script, we have created two variables:

  • $ globalName - this is global variable
  • $ localName - this is local a variable that is created inside the sayHello () function.

After creating the variable and function, the script calls sayHello (), which outputs "Hello Harry!" ... The script then tries to print the values \u200b\u200bof the two variables using the echo function. Here's what's going on:

  • As $ globalName was created outside the function, it is available anywhere in the script, so "Zoe" is displayed.
  • $ localName will only be available inside sayHello () function. Since the echo expression is outside the function, PHP does not allow access to the local variable. Instead, PHP assumes that the code will create a new variable named $ localName that will receive a default value of an empty string. this is why the second call to echo outputs the value "" for the $ localName variable.

Accessing global variables inside a function

To access a global variable out of function just write her name. But to access the global variable inside function, you must first declare the variable as global in the function using the global keyword:

Function myFunction () (global $ globalVariable; // Access to the global variable $ globalVariable)

If you don't, PHP assumes that you are creating or using a local variable.

Here's an example script that uses a global variable inside a function:

"; global $ globalName; echo" Hello $ globalName!
";) sayHello ();?\u003e

When executed, the script will output:

Hi Harry! Hi Zoya!

The sayHello () function uses the global keyword to declare the $ globalName variable as global. Then she can access the variable and display its value ("Zoe").

What are superglobals?

PHP has a special set of predefined global arrays that contain various information. Such arrays are called superglobals, since they are accessible from anywhere in the script, including the inner function space, and do not need to be defined using the global keyword.

Here is a list of superglobals available in PHP version 5.3:

  • $ GLOBALS - list of all global variables in the script (excluding superglobals)
  • $ _GET - contains a list of all form fields submitted by the browser using a GET request
  • $ _POST - contains a list of all form fields submitted by the browser using a POST request
  • $ _COOKIE - contains a list of all cookies sent by the browser
  • $ _REQUEST - contains all key / value combinations that are contained in the $ _GET, $ _POST, $ _COOKIE arrays
  • $ _FILES - contains a list of all files loaded by the browser
  • $ _SESSION - allows you to store and use session variables for the current browser
  • $ _SERVER - contains information about the server, such as the filename of the script being executed and the IP address of the browser.
  • $ _ENV - Contains a list of environment variables passed to PHP, for example CGI variables.
For example, you can use $ _GET to get the values \u200b\u200bof variables enclosed in the URL string of a script request, and display them on the page:

If you run the above script with the URL string http://www.example.com/script.php?yourName\u003dFred, it will output:

Hi Fred!

Warning! In a real script, you should never use such data transfer due to weak security. You should always check or filter your data.

The $ GLOBALS superglobal is very convenient to use because it allows you to organize access to global variables in a function without the need for the global keyword. For example:

";) sayHello (); // Prints" Hello, Zoe! "?\u003e

Static variables: they are somewhere nearby

When you create a local variable inside a function, it only exists while the function is running. When the function ends, the local variable disappears. When the function is called again, a new local variable is created.

This works great in most cases. This way the functions are self-contained and always work the same every time they are called.

However, there are situations where it would be convenient to create a local variable that "remembers" its value between function calls. Such a variable is called static.

To create a static variable in a function, you must use the static keyword before the variable name and be sure to set an initial value to it. For example:

Function myFunction () (static $ myVariable \u003d 0;)

Let's consider a situation when it is convenient to use a static variable. Let's say you create a function that, when called, creates a widget and displays the number of widgets already created. You can try writing code like this using a local variable:


"; echo createWidget ()." we have already created.
"; echo createWidget ()." we have already created.\u003e
"; ?>

But, since the $ numWidgets variable is created every time the function is called, we will get the following result:

We create some widgets ... 1 we have already created. 1 we have already created. 1 we have already created.

But using a static variable, we can store the value from one function call to the next:

"; echo createWidget ()." we have already created.
"; echo createWidget ()." we have already created.
"; echo createWidget ()."\u003e we have already created.
"; ?>

The script will now produce the expected output:

We create some widgets ... 1 we have already created. 2 we have already created. 3 we have already created.

Although a static variable retains its value between function calls, it is only valid when the script is executed. As soon as the script finishes its execution, all static variables are destroyed, as well as local and global variables.

That's all! Check the PHP documentation often.