Tutorial about global variables in PHP. How to use global, superglobal in PHP.
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
// $x is a global variable, $y is a defined global variable global $x; $y = 'var1'; $x = 'var2'; function example_func() { //global variable global $z; $z = 'test'; //static variable $static_var1 = 'static'; //defined static variable, it's faster when you define the variables static $static_var2; $static_var2 = 'static'; echo $x.' and '.$y; //you can see both of these } example_func(); echo $z; //you can see "test" //these statics are invisible or cause errors. 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
//This line prints your computers IP address 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.