Skip to content

PHP Super-Global Variables

Super-global as built-in or predefined variables in PHP, they are as follows,

  • $GLOBLAS
  • $_GET
  • $_POST
  • $_REQUEST
  • $_SESSION
  • $_COOKIE
  • $_FILES
  • $_SERVER
  • $_ENV

$GLOBALS

An associative array containing references to all variables which are currently defined in the global scope of the script.

Example

<?php
class exampleClass
{
    function exampleFunction()
    {
        $variable = "anothername";
       /*first i am going to print the $variable
       which is in outside the function*/

       /*if i do so....*/
       echo $variable; // its prints "anothername"
       /*so to print the variable outside the function*/
       echo $GLOBALS["variable"]; // prints "anyname"

    }
}
$variable = "anyname";
exampleClass::exampleFunction();
?>

GET

Informations sent from a form with the GET method is visible (displayed in the url). i.e. url changes to the submitted script name, the field name and values are appended with the url. Never ask username and password in GET method, even hidden variables are shown in the url. It has limit on the amount of information to send. A lot of webservers might complain about long url being submitted, 200 characters or more is problem.

POST

This method is more secure. Information sent through a socket to the webserver and its not visible in the url and it has no character limitations.

Example

Copy the below code in the file: form.php

<html>
 <body>
  <form name="my_form" action="show_method.php" method="post">

   <input type="text" name="first_name" />
   <input type="text" name="last_name" />
   <input type="submit" name="form_sub" value="Submit" />

  </form>
 </body>
</html>

In show_method.php,

<?php

   /*In POST method the url remains same as
http://localhost/showmethod.php

     In GET method the url will be
http://localhost/showmethod.php?first_name=ur_value
&?last_name=ur_value
     it will be printed as echo $_GET['first_name'];
  */
   echo $_POST['first_name'];
   echo $_POST['last_name'];

   /*This prints the value entered in the
box*/

   print_r($_REQUEST);

?>
POST GET
The data sent by this method goes through HTTP headers, security depends upon HTTP Protocol. The data sent by this method will be appended in the url, which will be visible to everyone. Example: index.php? cmpny=oracle &dept= gmss
Secure Insecure
This method can be used to send ASCII as well as binary datas. This can’t be used to send binary data.
No restriction on data size. Restricted to send minimum characters only.
Variables from this method can accessed by $_POST[‘var_name’] Variables from this method can accessed by $_GET[‘var_name’]

$_REQUEST

The $_REQUEST is an associative array that by default contains $_GET, $_POST and $_COOKIE. $_REQUEST method should be used mostly.

For example, assume you have assigned same variable for GET and POST, when you receive it in $_REQUEST method, it receives both variables from GET and POST but it cannot differentiate which is GET and which is POST, so you can’t be sure where the variable is actually coming from, is it GET, POST or COOKIE. You should know about the variable order. Check your phpinfo() [http://localhost/xampp/phpinfo.php] or php.ini file, by default the variable_order configuration directive is set to “EGPCS”. This tells PHP to introduce variables in this order:

  • Environment variables
  • GET
  • POST
  • Cookies
  • Server variables ( Built-in variables )

$_SESSION

Session management is a mechanism to maintain state about a series of request from the same user across some period of time. That is, the term “Session” refers to the time period, a user is at a particular website. A visitor accessing your website is assigned a unique id, which is called as session id. This is stored in the cookie on the user side or is propagated in the URL.

Starting a Session

A Session is initialized by using session_start(). session_start() creates a session or resumes the current one based on a session identifier.

Configuring Session

Session management is configured by php.ini file. To have a user’s session start as soon as the user visits the website, the session.auto_start flag must be set to 1.

Session Functions

The following table shows the most common session functions,

Functions Description
session_start() Starts new session if does not exist, continues current session if exists.
session_unset() Unset all the session variables.
session_destroy() Kills session.

Example

<?php
	session_start();
	$_SESSION['vars'] = "I am a session variable";
	echo $_SESSION['vars']; //prints I am a session variable
?>
<?php
	session_start();
	$_SESSION['vars'] = "I am a session variable";
	session_unset($_SESSION['vars']);
	echo $_SESSION['vars']; 
	/*prints nothing, the session variable made unset, this 
	does only affects the local $_SESSION variable instance
 but not the session data in the session storage.*/
?>
<?php
	session_start();
	$_SESSION['vars'] = "I am a session variable";
	session_destroy();
	echo $_SESSION['vars']; 
	/*prints nothing, destroys the session data that 
	is stored in the session storage.*/
?>

$_COOKIE

PHP supports HTTP cookies. Cookies are the mechanism for storing data in the remote browsers and thus tracking or identifying the return users. A cookie can be set by using setcookie() or setrawcookie() functions. The function must be called before any output is sent to the browsers. This is the same limitation as header() has. You can use the output buffering functions to delay the scripts output until you have decided whether or not to set any cookie or send any headers.

<?php

/* cookie arguments, all arguments except the name argument are
optional. you may also replace an argument with an empty("") string
to skip. expire argument cannot be skipped with empty string
because it is a integer so use zero(0) instead */

setcookie($cookie_name, $cookie_value, expire_time, path, domain,
secure, httponly);

// To set a cookie

$value = "maybe your username";
setcookie("cokkie_test",$value, time()+3600); // expires in 1 hour
setcookie("cokkie_test",$value, time()+3600, "particular_path/",
"anysite.com", 1,0); 

/*argument secure indicate whether the cookie should only 
transmitted over HTTPS connection from the client. the default
is false. when set true the cookie will only be set if a secure 
connection exists */

/*argument httponly, when true the cookie will be made accessible
only through HTTP protocol, this means the cookie wont be accessible
by scripting language like javascript. this help to reduce XSS
attack*/

?>

$_FILES

This array will contain all the upload file informations.

Example

We will see how to upload a image. Copy the below code in the file: form.html

<html>
 <body>
  <form name="my_form" action="upload.php" method="post"
enctype="multipart/form-data">

   <input type="file" name="upload_file" />
   <input type="submit" name="form_sub" value="Submit" />

  </form>
 </body>
</html>

In upload.php,

<?php
print_r($_FILES); /* this prints

Array
(
    [upload_file] => Array
        (
            [name] => file_name.file_type
            [type] => application/file
            [tmp_name] => D:\xampp\tmp\php2F67.tmp
            [error] => 0
            [size] => 39424
        )
)
*/

/*To upload the file*/

$upload_path = "uploadedfiles/"; /*Create a folder*/
if($_FILES['upload_file']['type'] == "image/gif" ||
$_FILES['upload_file']['type'] == "image/jpg" ||
$_FILES['upload_file']['type'] == "image/jpeg")
{
    $upload = move_uploaded_file($_FILES['upload_file']['tmp_name'],
$upload_path.$_FILES['upload_file']['name']);/*upload the file*/
    if($upload)
       echo "Image Uploaded";
    else
       echo "Error in upload";
}
else
{
    echo "Invalid File";
}

?>

$_SERVER

$_SERVER is an array containing information such as header, paths and script locations. The entries in this array are created by the web server. The following table shows most common server elements.

Variables Description
$_SERVER[‘PHP_SELF’] The file name of the currently executing script. For instance, element in a script at a address http://www.example.com/test/create/page.php would be /test/create/page.php.
$_SERVER[‘SERVER_ADDR’] The ip address of the sever, which the current script is executing.
$_SERVER[‘SERVER_NAME’] The name of the sever host.
$_SERVER[‘QUERY_STRING’] The query string, which the page was accessed.
$_SERVER[‘REMOTE_ADDR’] The ip address from which the user is viewing the current page.
$_SERVER[‘REQUEST_URI’] To access the URI of the current page.

$_ENV

Environmental variables, 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. try,

<?php
	print_r($_ENV);
?>

<< Back

PHP Classes & Functions

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: