Predefined Variables in PHP: For complete beginners
This an overview made for beginners: and introduction to predefined variables in PHP. We’ll go over what they are, where you’ve probably seen them, and how and when to use them.
What Are Predefined Variables?
Predefined variables in PHP are exactly what they sound like — variables in the PHP language that have been defined already. They can use used in any PHP script, with no need to create them yourself. They serve a purpose that is commonly used among programmers repeatedly, such as passing information from a form to a PHP script ($_POST would be used for this).
Here is the list of currently defined variables in PHP. Of course, you don’t need to understand all of these quite yet, but they can come in handy for any PHP developer.
- $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
All of these variables interact with the current server in some way. This means their purpose is to either get information from the server (e.g. Find the IP address of the user) or translate information to the server (e.g. send a user’s information from a form through the server to be handled by a PHP script.)
Let’s now get a closer look at some of the most commonly used predefined variables.
$_SERVER
This variable is an array of values, with the values containing information about the server.
If you don’t know what an array is, it’s quite simple: it is a collection of values, put into one component. For example, an array of numbers would be “1, 4, 6, 3, 3”. All these numbers can be stored in one place, called an array. The array can then be assigned to a variable name, like “$numbers”. There are more formal definitions of an array, as this definition may not be 100% ‘accurate’. However, it’s a good outline and way to think of arrays.
Let’s say we’re creating a fluid layout, and because different browsers handle pixels differently, we want to determine the browser type of the user so we can lead them to a specified stylesheet. This way, we can make sure a fluid layout never breaks.
In the PHP $_SERVER array (collection), there is one piece called “HTTP_USER_AGENT”. This piece of the array (index of the array) contains the user’s browser information. We can call it like so:
$_SERVER["HTTP_USER_AGENT"];
To see it in action, let’s echo it out:
The code above will return browser information in the form of a string. My browser information looks like this:
Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)
I won’t get too into it, but from here on we can see how we can use this information to specify a certain stylesheet for a user. If we store that String in a variable, (or part of the string), and send it through an if/else statement, we can give the user the correct stylesheet.
Note: This just pseudo code below!
$browserType = $_SERVER["HTTP_USER_AGENT"]; if $browserType = "Mozilla. " then [switch user to the Mozilla Firefox stylesheet] else if $browserType = "Internet Explorer. " then [switch user to the IE stylesheet] else [use the default stylesheet]
Here are some of the other indexes in the $_SERVER array:
- Get the user’s IP Address: REMOTE_ADDR
- Get the hosting server’s name: SERVER_NAME
- Retrieve the referrer URL: HTTP_REFERER
- Retrieves the server identification string: SERVER_SOFTWARE
- Retrieves the pathname of the current running script: SCRIPT_FILENAME
- Retrieves the current page URL: SERVER_PROTOCOL
- Retrieves how the script was requested (Did it use “Get” or “Post”): REQUEST_METHOD
If you don’t understand what they do based on the general description given above, do some more research on them, as well as try them out!
$_POST
This predefined variable is very commonly used, and incredibly useful when working with forms. You’ve probably seen this one before if you’ve ever tried to learn PHP.
The $_POST variable is linked to a method in PHP, called “post”, respectively. This method is often used in forms that need to send data to a PHP script. An example of this would be a sign-up form: the user enters in data to the form, the form uses the post method to send it to the specified script, and the script can then process the data.
Easy enough, right? Well in order to carry the input from the form over to the script (in the example above, ‘phpscript.php’), it puts the data in an array and assigns that array to a variable: $_POST. So, the $_POST variable contains all the data sent through the post method.
To specify the names of the indexes in the $_POST array, we clarify names in the input tags within the form:
After using the name=”” attribute, we can easily find that data in our $_POST variable array:
We have retrieved the data from a form, sent it to a PHP script, and can now work with it inside the PHP script. Using that, we can assign the username to a variable within our PHP script, manipulate it, or send it to a database.
$_GET
The $_GET variable is very similar to the $_POST variable in that it can work with forms and a PHP method called “get”.
The difference is that the get method will send information through the URL, like so:
http://example.com/?name=Kayla&website=https://theguerrilla.agency
Let’s break that up a bit. We can see the example website: http://example.com. Then, we see a question mark (?). This question mark means that everything following it within this URL is now associated with the form, and contains the variables. We then see “name=Kayla”. This would be if I were to create an input field named “name”, and input “Kayla” for the variable to be passed:
Next, an ampersand (&) that will connect all the field names and variables. Finally, our second piece of data, named “website” with a value of “https://theguerrilla.agency”.
The URL will go to the page where the form wants us to go (the location of the action=”” attribute). In our case, ‘thankyou.php’. It can display a thank you message, or whatever other type of content you’d like to display. In addition, this page can retrieve data with PHP:
A better example of $_GET in action is:
Of course, that’s fairly useless, but you see how it could be used if needed. The point of $_GET is to easily pass information from a form that the user enters, and provide it to the next page. This helpful for any sort of non-secure information, such as the number of items to add to a shopping cart, or posting a website to a database.
You would not, however, ever want to use $_GET for a signup form or anything that uses secure information. Otherwise, important information (like a password) would be sent through the URL and could be seen by anyone that could view the computer screen.
Conclusion
Hopefully, with a more in-depth overview of these three predefined variables, it can get you started in understanding the rest of them. A great place to get started is the PHP Manual itself.
In a future tutorial, I really want to go over the $_COOKIE variable, and how one can use cookies to identify users and work with specific users to the programmer’s advantage.
PHP Predefined Variables
Any PHP script has access to a number of predefined variables. However, many of them are dependent on web server software, PHP version and other factors. Some of these variables are not available for a script running in command line mode. The $GLOBALS variable stores references of all globally available predefined varibles. Most of these variables are displayed by phpinfo.php Some of commonly used predefined variables are explained here.
$_SERVER
This is an array variable that contains information about HTTP headers, script and environment. Following are some of prominent members of this array
PHP_SELF − stores filename of currently executing script. For example, a script in test folder of document root of a local server returns its path as follows −
Example
Output
This results in following output in browser with http://localhost/test/testscript.php URL
SERVER_ADDR − This property of array returns The IP address of the server under which the current script is executing.
SERVER_NAME − Name of server hostunder which the current script is executing.In case of a erver running locally, localhost is returned
QUERY_STRING − A query string is the string of key=value pairs separated by & symbol and appended to URL after ? symbol. For example, http://localhost/testscript?name=xyz&age=20 URL returns trailing query string
REQUEST_METHOD − HTTP request method used for accessing a URL, such as POST, GET, POST, PUT or DELETE. In above query string example, a URL attached to query string wirh ? symbol requests the page with GET method
DOCUMENT_ROOT − returns name of directory on server that is configured as document root. On XAMPP apache server it returns htdocs as name of document root
DOCUMENT_ROOT − This is a string denoting the user agent (browser) being which is accessing the page.
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
REMOTE_ADDR − IP address of machine from which the user is viewing the current page.
SERVER_PORT − port number on which the web server is listening to incoming request. Default is 80
$_GET
By default, client browser sends a request for URL on the server by HTTP GET method. A query string attached to URL may contain key=value pairs concatenated by & symbol. The $_GET associative array stores these key value pairs
Assuming that the URL in browser is http://localhost/testscript?name=xyz&age=20
Example
Output
This will produce following result −
$_POST
An associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request.
Data is sent to a PHP script using POST method by specifying action=POST in a HTML form test.html as below −
The PHP script is as follows −
Example
Output
This will produce following result −
$_FILES
This variable is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data.
In the PHP script, _FILES variable is accessed as follows −
Example
Output
Array ( [file] => Array ( [name] => hello.html [type] => text/html [tmp_name] => C:\xampp\tmp\php9647.tmp [error] => 0 [size] => 56 ) )
$_REQUEST
This variable is an associative array providing contents of $_GET, $_POST and $_COOKIE predefined variables.
$_SESSION
This variable is an associative array of variables representing HTTP session.
$_ENV
An array of environment variables form this predefined variable. These variables are imported into PHP’s global namespace.
$_COOKIE
Server can store certain data in client’s computer in the form of cookies. These cookies are transmitted every time a request is made. The _COOKIE variable is an associative array of cookie variables and their values.