PHPBuilder - Fundamentals of PHP Superglobals Page 2



RSS Twitter
Articles Php Functions

Fundamentals of PHP Superglobals - Page 2

by: Ian Gilfillan
|
October 18, 2007

$_POST

The HTTP POST method is very similar, and is conventionally used when the contents of the form are going to change something. But the mechanics are the same, except they use the $_POST superglobal, for example:


postform.html
<form method='POST' action='postform.php'>
<input type='text' name='email'>
<input type='submit' value='Submit your email'>
</form>

postform.php
<?php
print $_POST['email'];
?>


$_POST has been around since PHP 4.1.0. Before that, $HTTP_POST_VARS was used (though this was not automatically global).


$_REQUEST

It's preferable to use the specific superglobal that is intended to contain the variables. If you know a variable is being passed using the GET method, use $_GET. If you know it's being POSTED, use $_POST. But there are times when you may not be sure. I recently came across a script that received the same variable from both the GET and POST methods, depending on how it was called. There's an easy option in this case - use $_REQUEST. It contains all variables passed from both methods, as well as those contained in $_COOKIE (discussed below). In any of the examples above, you could replace $_POST or $_GET with $REQUEST, and the result would be identical.
$_REQUEST has also been around since PHP 4.1.0. Before version 4.3.0, in addition to the contents of $_POST, $_GET and $_COOKIE, $_REQUEST also contained $_FILES (discussed below) information.


$_GLOBALS

The final superglobal that can be used for forms is $_GLOBALS. It's really a super superglobal, as it contains references to all variables in the script's global scope. Replacing $_POST or $_GET with $_GLOBALS in the examples above would also have the identical results. $_GLOBALS has been around since PHP 3.0.0


$_COOKIE

Contains all variables passed from HTTP cookies. $_COOKIE has been around since PHP 4.1.0. Before that, $HTTP_COOKIE_VARS was used (though this was not automatically global).


$_SESSION

This superglobal keeps all session variables. See the article Maintaining State with PHP4 Sessions for more info, or the documentation on PHP sessions.

$_SESSION, as with most of the superglobals, has been around since PHP 4.1.0. Before that, $HTTP_SESSION_VARS was used (though this was not automatically global).

$_SERVER

This superglobal contains information passed from the web server. Web servers differ, so all of the following may not be available under your setup. If you're running PHP from the command line, most of these become pretty meaningless. Here's a list of elements in the array:


  • argc: The number of parameters passed to the script from the command line. Commonly used for basic validation, for example:
    if ($_SERVER['arcg'] == 0) {
      echo 'Please pass at least one parameter to this script';
      exit;
    }
    
  • argv: An array containing either the query string (when called via HTTP GET), or the parameters (when called from the command line).
  • AUTH_TYPE: The authentication type when doing HTTP authentication.
  • GATEWAY_INTERFACE: The CGI specification used by the server. Probably not that useful, as in most cases this will be CGI/1.1. The spec for 1.2 hasn't been finalised yet, and 1.1 has been out long enough to be implemented by almost every web server this century.
  • DOCUMENT_ROOT: The document's root directory, defined in the server config. For example: /var/www/phpbuilder
  • HTTP_ACCEPT: List of media types that the client accepts. Not all clients supply this.
  • HTTP_ACCEPT_CHARSET: The character set the client prefers, for example iso-8859-1,*,utf-8.
  • HTTP_ACCEPT_ENCODING: What encoding the client accepts, if any, for example gzip. This is used by functions such as ob_gzhandler to determine whether to send compressed data or not.
  • HTTP_ACCEPT_LANGUAGE: Language the client prefers, e.g en.
  • HTTP_CONNECTION: The preferred option for the connection, e.g. close or keep-alive. By default, HTTP 1.1 uses persistent connections (keep-alive).
  • HTTP_HOST: The host, if any, for example phpbuilder.com.
  • HTTP_REFERER: The page from which the client followed a link (was refered) to get to the current page. Years ago, when I first came across this, I thought it meant the previous page, even if you typed the URL in the browser address bar. The script doesn't have access to whatever page you were previously surfing however, only pages that link to it. It used to be common to check this as a security feature, attempting to ensure that you only access a page from a desired source. It still does no harm, but some clients can modify this, so it isn't entirely reliable.
  • HTTP_USER_AGENT: Details of the client. This is used to generate those stats you commonly see on sites, telling you what proportion of readers use a particular browser or operating system. An example from the client I'm using to write this article: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.6
  • PATH_TRANSLATED: Filesystem-based path, after any mapping from virtual to real. According to the CGI spec, it should only be present if PATH_INFO is defined.
  • PHP_AUTH_DIGEST: The Authorization header from the client, if Apache Digest HTTP authentication is being used.
  • PHP_AUTH_PW: The password supplied by the client when doing HTTP authentication (With ISAPI this is only supported by PHP5).
  • PHP_AUTH_USER: The username supplied by the client when doing HTTP authentication (With ISAPI this is only supported by PHP5).
  • PHP_SELF: This contains the filename of the current script (e.g /dir/script.php). It's also commonly used in creating self-referential links, for example:
    $html = "<FORM NAME='sameold' METHOD='POST' 
    ACTION='.$_SERVER['SCRIPT_NAME'].'^gt;";
    

    Since PHP 4.3.0, it also contains the script name when running from the command line.

  • QUERY_STRING: The query string, for example var1=2&var2=3.
  • REMOTE_ADDR: The remote IP used to access the script.
  • REMOTE_HOST: The remote host, based on the IP. Most web servers (wisely) do not waste resources automatically doing the reverse dns lookup required to determine this.
  • REMOTE_PORT: The remote port being used by the client to communicate with the server.
  • REQUEST_METHOD: One of GET, POST, HEAD or PUT.
  • REQUEST_TIME: A PHP 5.1.0 addition, this is the timestamp of the request.
  • REQUEST_URI: The URI given to access the script, for example /form.php.
  • SCRIPT_FILENAME: The absolute path and name of the current script, for example /var/www/phpbuilder/form.php. If run from the command line, the path can also be relative if that's what was specified.
  • SCRIPT_NAME: Path to the current script. It's also commonly used in creating self-referential links, for example:
    $html = "<FORM NAME='sameold' METHOD='POST' 
    ACTION='.$_SERVER['SCRIPT_NAME'].'>";
    
  • SERVER_ADMIN: The server administrator value, as specified in the web server configuration, for example webmaster@phpbuilder.com.
  • SERVER_NAME: The name of the server host (or virtual host) under which the script is running, e.g phpbuilder.com.
  • SERVER_PORT: The server port used for communication, usually 80.
  • SERVER_PROTOCOL: Usually HTTP/1.1 these days.
  • SERVER_SIGNATURE: The server version and host name, for example Apache/1.3.33 Server at phpbuilder.com Port 80
  • SERVER_SOFTWARE: Server id, given in the headers. Usually contains the server version, PHP version, any SSL versions.
It's easy to see what the results would be in your own environment. Create a simple script to loop through and display all elements of the array.


<?
// server.php
foreach ($_SERVER as $key=>$value)
   echo "$key $value<br>" ;
?<


Calling this script with a couple of parameters, i.e. http://phpbuilder.co.za/server.php?var1=2&var2=3, produces the following output:


DOCUMENT_ROOT /var/www/phpbuilder
HTTP_ACCEPT text/xml,application/xml,application/xhtml+xml, text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
HTTP_ACCEPT_CHARSET ISO-8859-1,utf-8;q=0.7,*;q=0.7
HTTP_ACCEPT_ENCODING gzip,deflate
HTTP_ACCEPT_LANGUAGE en-us,en;q=0.5
HTTP_CONNECTION keep-alive
HTTP_COOKIE MANTIS_PROJECT_COOKIE=8; MANTIS_VIEW_ALL_COOKIE=3
HTTP_HOST phpbuilder.co.za
HTTP_USER_AGENT Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.6
HTTP_VIA 1.1 cbs-cache1 (NetCache NetApp/5.6.2D16)
HTTP_X_FORWARDED_FOR 165.146.136.106
PATH /bin:/usr/bin:/usr/local/bin
REMOTE_ADDR 198.54.202.18
REMOTE_PORT 23171
SCRIPT_FILENAME /var/www/phpbuilder/server.php
SERVER_ADDR 216.32.75.242
SERVER_ADMIN webmaster@phpbuilder.co.za
SERVER_NAME phpbuilder.co.za
SERVER_PORT 80
SERVER_SIGNATURE
Apache/1.3.33 Server at phpbuilder.co.za Port 80
SERVER_SOFTWARE Apache/1.3.33 (Debian GNU/Linux) PHP/4.3.10-13 mod_ssl/2.8.22 OpenSSL/0.9.7d
GATEWAY_INTERFACE CGI/1.1
SERVER_PROTOCOL HTTP/1.1
REQUEST_METHOD GET
QUERY_STRING var1=2&var2=3
REQUEST_URI /server.php?var1=2&var2=3
SCRIPT_NAME /server.php
PATH_TRANSLATED /var/www/phpbuilder/server.php
PHP_SELF /server.php
argv Array
argc 1


$_SERVER has also been around since PHP 4.1.0. Before that, $HTTP_SERVER_VARS was used (though this was not automatically global).


$_ENV

This varies according to the PHP environment. In my environment, the displaying the entire array by calling the script env.php, below:


<?
// env.php
foreach ($_ENV as $key=>$value)
   echo "$key $value<br>" ;
?<


produces


LANG C
PATH /bin:/usr/bin:/usr/local/bin


$_FILES

When uploading files with an HTTP POST, these elements are populated to provide feedback to the script.
  • $_FILES['userfile']['error']: The error code from the upload. These could be any of:
    • UPLOAD_ERR_OK: 0, successful upload.
    • UPLOAD_ERR_INI_SIZE: 1, file size exceeds upload_max_filesize from the php.ini config file.
    • UPLOAD_ERR_FORM_SIZE: 2, file size exceeds MAX_FILE_SIZE from the HTML form.
    • UPLOAD_ERR_PARTIAL: 3, the file was only partially uploaded.
    • UPLOAD_ERR_NO_FILE: 4, no file uploaded
    • UPLOAD_ERR_NO_TMP_DIR: 6, no temporary directory
  • $_FILES['userfile']['name']: The name of the file on the client.
  • $_FILES['userfile']['size']: The uploaded file's size in bytes.
  • $_FILES['userfile']['tmp_name']: The temporary name of the uploaded file on the server.
  • $_FILES['userfile']['type']: The file's mime type, for example /image/png.


$_FILES has also been around since PHP 4.1.0. Before that, $HTTP_POST_FILES was used (though this was not automatically global).


Conclusion

The PHP superglobals are likely to remain unchanged for a while. After all the recent changes, and resultant confusion for new developers, now's a good time to get it right and learn how to use them properly. Good luck!



« Previous Page
1
|
2

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Ian Gilfillan

Comment:



Comment:

(Maximum characters: 1200). You have characters left.