PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages etc. All this information is defined in some predefined variables.

Following is the list of PHP predefined variables:

  • Superglobals — Superglobals are built-in variables that are always available in all scopes.
  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — The previous error message
  • $HTTP_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to script

Superglobals

Several predefined variables in PHP are “superglobals”, which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods. They defines useful information about files, servers, post, get parameters etc.

These superglobal variable’s definitions are given below:

1. $GLOBALS

An associative array containing references to all variables which are currently defined in the global scope of the script in our code. The variable names can be accessed by using the keys of the array. It means to access any global variable, use the name of the variable as the key of the $GLOBALS array to access its value.

$GLOBALS Example:-

<?php

function test_globals() {
    $var = "My local variable inside function";

    echo '$var in global scope: ' . $GLOBALS["var "] . "\n";
    echo '$var in local scope: ' . $foo . "\n";
}

$var= "My Global variable outside function";
test_globals();
?>

$GLOBALS Example Output:

The above example will output something similar to:

$var in global scope: My Global variable outside function
$var in local scope: My local variable inside function

Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.

2. $_SERVER

$_SEREVR is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. It means depending upon the settings of the server, they may display only some variables in this array and may not display some others.

$_SERVER Indices

All indices of the array $_SERVER are explained below:

You may or may not find any of the following elements in $_SERVER. Note that some of these will be available only if running PHP on the command line.

PHP_SELF:-

The filename of the currently executing script, relative to the document root. For instance, $_SERVER[‘PHP_SELF’] in a script at the address https://codingambitions.com/example/example.php would be  /example/example.php . The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.

argv :-

Array of arguments passed to the script. When the script is run on the command line, this gives access to the all command line parameters. When called via the GET method, this will give access to the query string

argc:-

It Contains the number of command line parameters passed to the script (if run on the command line).

GATEWAY_INTERFACE:-

What revision of the CGI specification the server is using; e.g. ‘CGI/1.1‘.

SERVER_ADDR:-

It will display the IP address of the server under which the current script is executing.

SERVER_NAME:-

It will display the name of the server host under which the current script is executing.

SERVER_SOFTWARE:-

It will display the Server identification string which is given in the headers when responding to requests.

SERVER_PROTOCOL:-

It will display the name and revision of the information protocol via which the page was requested; e.g. ‘HTTP/1.0‘;

REQUEST_METHOD:-

It will display the request method which was used to access the page; e.g. ‘GET‘, ‘HEAD‘, ‘POST‘, ‘PUT‘.

REQUEST_TIME:-

It will display the timestamp of the start of the request. It is Only Available since PHP 5.1.0.

REQUEST_TIME_FLOAT:-

It will display the timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0.

QUERY_STRING:-

It will display the query string, if any, via which the page was accessed.

DOCUMENT_ROOT:-

This will display the document root directory under which the current script is executing, as defined in the server’s configuration file.

HTTP_ACCEPT:-

Contents of the Accept: header from the current request, if there is one.

‘HTTP_ACCEPT_CHARSET’

Contents of the Accept-Charset: header from the current request, if there is one. Example: ‘iso-8859-1,*,utf-8‘.

‘HTTP_ACCEPT_ENCODING’

Contents of the Accept-Encoding: header from the current request, if there is one. Example: ‘gzip‘.

‘HTTP_ACCEPT_LANGUAGE’

Contents of the Accept-Language: header from the current request, if there is one. Example: ‘en‘.

‘HTTP_CONNECTION’

Contents of the Connection: header from the current request, if there is one. Example: ‘Keep-Alive‘.

‘HTTP_HOST’

Contents of the Host: header from the current request, if there is one.

‘HTTP_REFERER’

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent or we can say browser. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

‘HTTP_USER_AGENT’

It will display the contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).

‘HTTPS’

Set to a non-empty value if the script was queried through the HTTPS protocol.

‘REMOTE_ADDR’

It will display the remote IP address from which the user is viewing the current page.

‘REMOTE_HOST’

It will display the remote host name from which the user is viewing the current page.

Note: Your web server must be configured to create this variable. For example in Apache you’ll need HostnameLookups On inside httpd.conf for it to exist.

‘REMOTE_PORT’

It will display the port being used on the user’s machine to communicate with the web server.

‘REMOTE_USER’

The authenticated user.

‘REDIRECT_REMOTE_USER’

It will display the authenticated user if the request is internally redirected.

‘SCRIPT_FILENAME’

It will display the absolute pathname of the currently executing script.

‘SERVER_ADMIN’

It will display the value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file on your server.

‘SERVER_PORT’

It will display the port on the server machine being used by the web server for communication. For default setups, this will be ‘80‘; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

‘SERVER_SIGNATURE’

It will display the string containing the server version and virtual host name which are added to server-generated pages, if enabled.

‘PATH_TRANSLATED’

It will display the Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

‘SCRIPT_NAME’

It will display the contains the current script’s path. This is useful for pages which need to point to themselves.

‘REQUEST_URI’

It will display the URI which was given in order to access this page; for instance, ‘/index.html‘.

‘PHP_AUTH_DIGEST’

When doing Digest HTTP authentication this variable is set to the ‘Authorization’ header sent by the client (which you can then use to make the appropriate validation on its basis).

‘PHP_AUTH_USER

‘When doing HTTP authentication this variable is set to the username provided by the user.

‘PHP_AUTH_PW’

When doing HTTP authentication this variable is set to the password provided by the user.

‘AUTH_TYPE’

When doing HTTP authentication this variable is set to the authentication type.

‘PATH_INFO’

It will display the any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL https://www.codingambitions.com/php/path_info.php/some/stuff?var1=bar, then $_SERVER[‘PATH_INFO’] would contain /some/stuff.

‘ORIG_PATH_INFO’

It will display the original version of ‘PATH_INFO’ before processed by PHP.

$_SERVER Example:-

You can check this array indices values by printing it. Here name of my file is server_array.php.

<?php

echo"<pre>";
print_r($_SERVER);
echo"</pre>";

?>

$_SERVER Example Output:

This will print the following output on the server file.

Array
(
    [PATH] => /usr/local/bin:/usr/bin:/bin
    [TEMP] => /tmp
    [TMP] => /tmp
    [TMPDIR] => /tmp
    [PWD] => /
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
    [HTTP_ACCEPT_ENCODING] => gzip, deflate, br
    [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.9
    [HTTP_CONNECTION] => keep-alive
    [CONTENT_LENGTH] => 0
    [HTTP_COOKIE] => wordpress_test_cookie=WP+Cookie+check; icegram_campaign_shown_166=1; wp-settings-time-1=1584271860; wp-settings-1=imgsize%3Dfull%26hidetb%3D1%26editor_plain_text_paste_warning%3D2%26libraryContent%3Dbrowse%26edit_element_vcUIPanelWidth%3D650%26edit_element_vcUIPanelLeft%3D674px%26edit_element_vcUIPanelTop%3D74px%26editor%3Dtinymce%26post_dfw%3Doff; wordpress_logged_in_eb0babe0d77cd80981eaaf5ebf631765=admin%7C1584978133%7CtpTFsFTZ8owgAZsehPwgrqYsULf3uVxvgHOnGK2zowT%7Ccbc99791c87819800c1fd6c3093c8b5f9e703a9e5a1a1ea17ea45770e2bf37c9
    [HTTP_HOST] => codingambitions.com
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_SEC_FETCH_DEST] => document
    [HTTP_SEC_FETCH_SITE] => none
    [HTTP_SEC_FETCH_MODE] => navigate
    [HTTP_SEC_FETCH_USER] => ?1
    [HTTP_X_HTTPS] => 1
    [UNIQUE_ID] => XncQNsP9NWBhFPGKygU6MwAAAEE
    [SCRIPT_URL] => /server_array.php
    [SCRIPT_URI] => https://codingambitions.com/server_array.php
    [HTTPS] => on
    [SSL_TLS_SNI] => codingambitions.com
    [SERVER_SIGNATURE] => 
    [SERVER_SOFTWARE] => Apache
    [SERVER_NAME] => codingambitions.com
    [SERVER_ADDR] => 103.117.212.226
    [SERVER_PORT] => 443
    [REMOTE_ADDR] => 157.36.79.3
    [DOCUMENT_ROOT] => /home/techambi/public_html
    [REQUEST_SCHEME] => https
    [CONTEXT_PREFIX] => 
    [CONTEXT_DOCUMENT_ROOT] => /home/techambi/public_html
    [SERVER_ADMIN] => [email protected]
    [SCRIPT_FILENAME] => /home/techambi/public_html/server_array.php
    [REMOTE_PORT] => 57581
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] => 
    [REQUEST_URI] => /server_array.php
    [SCRIPT_NAME] => /server_array.php
    [PHP_SELF] => /server_array.php
    [REQUEST_TIME_FLOAT] => 1584861238.3124
    [REQUEST_TIME] => 1584861238
)

3. $_GET

It is an associative array of variables passed to the current script via the URL parameters (via query string). Note that the array is not only populated for GET requests, but rather for all requests with a query string.

$_GET Example:

Suppose the following is the path of the file you are sending data to via GET method:

https://codingambitions.com/server_array.php?username=codingambitions&name=codingambitions&[email protected]

Then inside this file print the $_GET array as given below:

<?php

echo"<pre>";
print_r($_GET);
echo"</pre>";

?>

$_GET Example Output:

It will display the following output in your file in the browser:

Array
(
    [username] => codingambitions
    [name] => codingambitions
    [email] => [email protected]
) 

And you can use these variables as $_GET[‘username’] etc.

4. $_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. This will display the array of the parameters passed to the current script via HTTP POST method.

$_POST Example:

Suppose you have posted the three parameters named username, name and email to the script as given below via submitting the form

<?php

echo"<pre>";
print_r($_POST);
echo"</pre>";

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Form Post Method Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Simple HTML Form</h2>
  <form action="/server_array.php" method='post'>
    <div class="form-group">
      <label for="username">Username:</label>
      <input type="text" class="form-control" id="username" placeholder="Enter Username" name="username">
    </div>
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

</body>
</html>

$_POST Example Output:-

It will display the following output after filling all fields:

Array
(
    [username] => codingambitions
    [name] => Coding Ambitions
    [email] => [email protected]
)

5. $_FILES

An associative array of items uploaded to the current script via the HTTP POST method.

The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name file1, as used in the example script above. This can be any name.

$_FILES[‘ file1 ‘][‘name’]:-

It will display the original name of the file on the client machine that is being uploaded.

$_FILES[‘ file1 ‘][‘type’]:-

The mime type of the file, if the browser provided this information. An example would be “image/gif”. This mime type is however not checked on the PHP side and therefore don’t take its value for granted.

$_FILES[‘file1’][‘size’]:-

The size, in bytes, of the uploaded file.

$_FILES[‘file1’][‘tmp_name’]:-

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES[‘file1’][‘error’]:-

It will display the errror_code associated with this file upload. If during file upload , there occurs some kind of error, then it will display the related error code.

PHP returns an appropriate error code along with the file array. In other words, the error might be found in $_FILES[‘file1’][‘error’]. Error odes are explained below:

UPLOAD_ERR_OK

There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL

The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE

No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Failed to write file to disk. It may be due to missing write permission of the directory where we are storing file.Introduced in PHP 5.1.0

UPLOAD_ERR_EXTENSION

A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

6. $_REQUEST

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. This global variable can be used to display the contents of every kind of request method e.g $_GET, $_POST and $_COOKIE etc.

7. $_SESSION

An associative array containing session variables available to the current script. 

$_SESSION Example:-

You can check its value by printing this variable as given below:

<?php

session_start();

$_SESSION['username'] = "codingambitions";
$_SESSION['name'] = "Coding Ambitions";
$_SESSION['email'] = "[email protected]";

echo"<pre>";
print_r($_SESSION);
echo"</pre>";

?>

$_SESSION Example output:-

It will display the following output:

Array
(
    [username] => codingambitions
    [name] => Coding Ambitions
    [email] => [email protected]
)

8. $_ENV

It is an associative array of variables passed to the current script via the environment method.

These variables are imported into PHP’s global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible.

$_ENV Example:-

You can check its values by printing it

<?php

echo"<pre>";
print_r($_ENV);
echo"</pre>";

?>

$_ENV Example Output:-

Array
(
    [PATH] => /usr/local/bin:/usr/bin:/bin
    [TEMP] => /tmp
    [TMP] => /tmp
    [TMPDIR] => /tmp
    [PWD] => /
)

9. $_COOKIE

It is an associative array of variables passed to the current script via HTTP Cookies.

$_COOKIE Example:-

Suppose a cookie username is set by the file.

<?php

$username = 'codingambitions';
setcookie("username", $username,time()+3600);

echo"<pre>";
print_r($_COOKIE);
echo"</pre>";

?>

$_COOKIE Example output:

Then it will display the following Output:

Array
(
    [username] => codingambitions
)

10. $php_errormsg

$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred,

This will print error message only if the track_errors configuration option is turned on (it defaults to off).

Warning: This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.

Use error_get_last() instead.

11. $http_response_header

It will display the HTTP response headers of the HTTP Request. It returns the array of the headers sent by the server in response to a HTTP request. Returned array is similar to the get_headers() function.

$http_response_header Example:-

<?php

file_get_contents("https://www.codingambitions.com/server_array.php");
echo"<pre>";
print_r($http_response_header);
echo"</pre>";

?>

$http_response_header Example output:-

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sun, 22 Mar 2020 08:24:19 GMT
    [2] => Server: Apache
    [3] => X-Powered-By: PHP/7.2.28
    [4] => Connection: close
    [5] => Content-Type: text/html; charset=UTF-8
)

12. $argc

Contains the number of arguments passed to the current script when running from the command line.

The script’s filename is always passed as an argument to the script, therefore the minimum value of $argc is 1. This variable is not available when register_argc_argv is disabled.

$argc Example:-

When executing the example file with: php my_script.php arg1 arg2 arg3.

The above example will output something similar to:

int(4)

13. $argv

It  displays an array of arguments passed to script .

The first argument $argv[0] is always the name that was used to run the script.

When executing the example with: php my_script.php arg1 arg2 arg3

The output will be something similar to:

array(4) {
  [0]=>
  string(13) "my_script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

Thats all about PHP Predefined Variables. I hope you have understood about the PHP Predefined variables.

Thanks!

Author

I am an core Android Developer with working knowledge of Kotlin and Java. And i also explore Flutter, React.js & Spring boot in extra time and having 8+ years of experience in this field. I have passion for solving complex problems. I love reading books and learning new challenging technologies in my extra time. Sharing my learning with others so that it can help others

Write A Comment