PHP Predefined Variables
ADVERTISEMENTS
PHP has many predefined variables to use in all scripts, these variables represent everything.
PHP Superglobals
PHP superglobals are built-in variables that are always available in all scopes.
There are several predefined superglobal variables listed here :
- $GLOBALS
- $_SERVER
- $_GET
- $_POST
- $_FILES
- $_COOKIE
- $_SESSION
- $_REQUEST
- $_ENV
$GLOBALS
PHP $GLOBALS variable reference or changed all variables into the global scope.
Example :
<?php
$var = "hello";
function Test() {
$var2 = "program";
$GLOBALS['var3'] = "good bye"; // Changed local scope to global scope
echo $GLOBALS['var'] . " " . $var2; // used outside variable inside function without argument with global scope
echo "<br/>";
}
Test();
echo $var3;
?>
Output :
hello program
good bye
good bye
$_SERVER
PHP $_SERVER is an array that contains information such as Headers, Path & Script locations, etc.
$_SERVER works with HTTP.
Example :
<?php
$array = $_SERVER;
foreach( $array as $key => $value ) {
echo $key . " => " . $value ."<br/>";
}
?>
$_GET
PHP $_GET accepts HTTP request to get data.
Such as a URL given as 'http://www.example.com/?var=john' that contains HTTP GET request.
Example :
<?php
$data = $_GET['var']; // This request get from URL /?var=john
echo $data;
?>
Output :
john
$_POST
PHP $_POST accepts HTTP request to post data. $_POST also used to post HTML form data after submission.
Such as an HTML form given here, After submitting data It will be posted via HTTP $_POST variable.
Example :
<?php
$var1 = $_POST['fname'];
$var2 = $_POST['lname'];
echo $var1 . " " . $var2;
?>
Output :
John Willey
$_REQUEST
PHP $_REQUEST accepts HTTP both request to Get and Post data.
$_REQUEST also accepts HTTP $_COOKIE requests.
Example :
<?php
// Understand from previous $_GET & $_POST example
$data = $_REQUEST['var'];
echo $data;
echo "<br/>"
$var1 = $_REQUEST['fname'];
$var2 = $_REQUEST['lname'];
echo $var1 . " " . $var2;
?>
Output :
john
John Willey
John Willey