PHP Global Variables

15 Jul, 2010
Tutorial about global variables in PHP. How to use global, superglobal in PHP.
Global variables can be used with pre defining or without. I like predefining, witch is faster and you get a nice view of your variables. Use supergobals carefully because they can cause harm, ruin you html or wipe out whole MySQL database.

Global Variables:

Globals work in a file, but not all around the project. For all around project you want to use superglobals.
Source code viewer
  1. // $x is a global variable, $y is a defined global variable
  2. global $x;
  3. $y = 'var1';
  4. $x = 'var2';
  5.  
  6. function example_func() {
  7. //global variable
  8. global $z;
  9. $z = 'test';
  10. //static variable
  11. $static_var1 = 'static';
  12. //defined static variable, it's faster when you define the variables
  13. static $static_var2;
  14. $static_var2 = 'static';
  15.  
  16. echo $x.' and '.$y; //you can see both of these
  17. }
  18.  
  19. example_func();
  20. echo $z; //you can see "test"
  21. //these statics are invisible or cause errors.
  22. echo $static_var1.$static_var2;
Programming Language: PHP

Superglobal variables:

Superglobals can be used absolutely anywhere in code.

$_SERVER
Variables witch are set by the web server.

Source code viewer
  1. //This line prints your computers IP address
  2. echo $_SERVER['REMOTE_ADDR'];
Programming Language: PHP

$_GET
An array of variables passed to the current script via the URL parameters. In single quotes you can put form or url variable names. This data can be unsafe if not properly handled.

$_POST
Variables provided via HTTP POST method. You can get form parameters by name if method is set to post. You can also send form data by using AJAX. Tutorial: CodeIgniter AJAX form submission.

$_COOKIE
Using this superglobal you can get variables from cookies. When making shop cart for an example.

$_FILES
If you send files trough forms using post method then you can catch them using this superglobal.

$_REQUEST
Variables provided by the GET, POST, and COOKIE superglobals, they come from client and which therefore cannot be trusted.

$GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script.