Like most languages, PHP variables are only valid in the scope in which they are declared. Hence, a variable declared in a function is not valid outside that
function and vice-versa. Free floating variables cannot be used in methods unless sent in as a parameter. Unless otherwise defined, all variables in PHP are local
and follow the basic scope rules.
A global variable overrides the scope boundaries and can be used across scopes. Global variables can be declared in general code or in a method AND are then
accessible across the entire file. This allows the creation of a variable in a condition or method that can then be used throughout the rest of the program.
Global variables are declared as follows:
global $x;
A step above global variables are superglobal variables. These are variables that are built into php that are available in all scopes. Most of the superglobal
variables operate as associative arrays. Here is a list of some of the superglobal variable arrays and their uses:
$_SERVER - information about the server includeing paths and files locations (ex: $_SERVER['SERVER_ADDR']; //returns IP address of server)
$_REQUEST - collect data sent to a page from an HTML form
$_GET - collect data sent by an HTML form with method=get OR to gather information from the url
$_POST - collect data sent by an HTML form with method=post
$_FILES - used in uploading and accessing files
$_SESSION - allows the storage/use of variables across multiple pages in a site
$_COOKIES - used to place small files from the server that help identify users
The $_GET Array
HTML forms that send information by method=GET attach the required information to the url of the action variable in name/value pairs. So, an input tag with
name attribute='first' that a user completes with "Bob", gets sent as the pair first=Bob. This pair gets appended to the target url as follows:
http://www.site.com/processForm.php?first=Bob.
The receiving page (processForm.php) can then receive the information using the $_GET array with the name as the index of the associative array.
$firstName=$_GET['first']; //$firstName now stored "Bob"
This concept of variables appended to the url can be utilized WITHOUT the need for a form to send the information. We can simply append information onto a url
and send it from page to page as desired.