PHP Super Global Variables

PHP Super Global Variables

Variables are “containers” for storing information. The main way to store information in the middle of a PHP program is by using a variable. PHP environment variables allow scripts to grab certain types of data dynamically from the server. A variable supports script flexibility in a potentially changing server environment.

PHP scripts contain variables that are local to our script and functions may have variables that are only accessible within that function, the PHP Superglobals represent data coming from URLs, HTML forms, cookies, sessions, and the Web server itself.

In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified.

Before coming to PHP Super Global Variables let’s talk about PHP Basics and its working areas.

Introduction to PHP

PHP (Hypertext Preprocessor) is a programming language that allows web developers to create dynamic content that interacts with databases. It is a HTML embedded language, most of its syntax are borrowed from C, JAVA, and PEARL.

PHP is a scripting language designed to fill the gap between SSI (Server Side Includes) and Perl, intended for the web environment. Its popularity derives from its C-like syntax, and its simplicity. PHP is currently divided into two major versions: PHP 4 and PHP 5 although PHP 4 is deprecated and is no longer developed or supplied with critical bug fixes. PHP 6 is currently under development.

Why PHP?

PHP is probably the most popular scripting language on the web. It is used to enhance web pages. With PHP, you can do things like create username and password login pages, check details from a form, create forums, picture galleries, and lot more.

PHP is known as a server-sided language. That’s because PHP doesn’t get executed on your computer, but on the computer you requested the page from. The results are then handed over to you, and displayed in your browser.

PHP is used to develop large Applications with the help of functions, Arrays, Strings, Loops, Operators, Variables and Methods.

How to start PHP?

Firstly we require Editor to write PHP codes. HTML, Netbeans, Visual Studio, Notepad++, Sublime Text, PHPEdit and many more are the editors where we can start writing programming codes.

Choose any of the editors for work. I’ll choose HTML because it’s easy to understand or navigate.

Here are the steps to create your first PHP file.

1. Create a new PHP file

Choose PHP and create file. Rename and save it to the needful place. Now we have blank page named test.php
 Update the title of your page <title>PHP Global</title>

Start coding from <body>Code goes here</body>

Every file will starts with the tag <?php ?>

Here is the example
<?php echo '<p>Hello World</p>'; ?>

PHP will be run on localhost on your computer. For that we need to install WampServer. After installing we need to shift our test.php file to www folder on wamp.

Here is the path Computer > Local Disk(C) > wamp > www

Keep your file folder on www folder. Start wampserver, you can see the red, orange and green indication on the bottom right side on your computer. Green indicates Server Online. Now choose option localhost and you can have localhost page.

Choose your file from Your Projects. Now you can add, edit the test.php file from HTML and run it on browser with help of wampserver.

I think all the above information can help you to understand PHP basics.It’s time to go through some programming terms and scripting methods. Before going to Super Global Variables let’s talk about PHP Variables.

PHP Variables

The main way to store information in the middle of a PHP program is by using a variable.

Here are the most important things to know about variables in PHP.

  • All variables in PHP are denoted with a dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
  • Variables used before they are assigned have default values.

Variable Scope

Scope can be defined as the range of availability a variable has to the program in which it is declared.

PHP variables can be one of four scope types:

  • Local variables
  • Global variables
  • Static variables

PHP Global Variables – Superglobals

Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in all scopes.

Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file.

The PHP Superglobal variables are:

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

PHP $GLOBALS

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script.

$GLOBAL is a php super global variable which can be used instead of ‘global’ keyword to access variables from global scope, the variables which can be accessed from anywhere in a php script even within functions or methods.

<?php
     $x = 15;
     $y = 20;
     function addit()
     {
            $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
     }
     addit();
     echo $z;
?>

In this statement Z represents GLOBAL because it can access the values of x and y from outside of the function.

PHP $_SERVER

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

<?php
     echo $_SERVER['PHP_SELF'];
     echo "<br>";
     echo $_SERVER['SERVER_NAME'];
     echo "<br>";
     echo $_SERVER['HTTP_HOST'];
     echo "<br>";
     echo $_SERVER['SCRIPT_NAME'];
?>

We’ll get this result

/roshni/test.php
localhost
localhost
/roshni/test.php

PHP $_REQUEST

$_RESUEST is used to collect data after submitting an HTML form. We can collect the value of the input field:

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
     Name: <input type="text" name="name">
     <input type="submit">
</form>
<?php
     if(isset($_REQUEST['name']))
     {
            echo $_REQUEST['name'];
     }
?>
php request super globals

PHP $_GET

PHP $_GET can also be used to collect form data after submitting an HTML form with method=”get”.

$_GET can also collect data sent in the URL.

<a href="test.php?subject=PHP&web=localhost/roshni/test.php">Test $GET</a>
<?php
     if(isset($_GET['subject']))
     {
          echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
      }
?>
php get super global variable

PHP $_POST

PHP $_POST is widely used to collect form data after submitting an HTML form with method=”post”. $_POST is also widely used to pass variables.

<a href="test.php?subject=PHP&web=http://localhost/roshni/test.php">Test $POST</a>
<?php
            if(isset($_POST['subject']))
            {
                   echo "Study " . $_POST['subject'] . " at " . $_POST['web'];
            }
?>
php post super global variable

If you wish to use another PHP file to process form data, replace that with the filename of your choice.

Here is the file code.

<form method="post" action="process.php">
    Name:<input type="text" name="name" /><br />
    Phone:<input type="text" name="phone" /><br />
    <input type="submit" value="submit" name="submit" />
</form>
php post super global variable

Here is the Process file for data processing.

<?php
    $name = $_POST['name'];
    $phone = $_POST['phone'];  
    echo "hello {$name}!<br />You'r phone number is $phone.";
?>
php post super global variable

PHP $_FILES

Manipulating files is a basic necessity for serious programmers and PHP gives makes it easy for creating, uploading, and editing files.

PHP File Open/Read/Close

PHP Open File – fopen() & fread()

<?php
     $myfile = fopen("new-text.txt", "r");
     echo fread($myfile,filesize("new-text.txt"));
?>
php files super global variable

PHP Close File – fclose()

<?php
     $myfile = fopen("new-text.txt", "r");
     fclose($myfile);
?>

File Upload

A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.

Here is the form code.

<form action="upload_file.php" method="post" enctype="multipart/form-data">
     <label for="file">Filename:</label>
     <input type="file" name="file" id="file"><br>
     <input type="submit" name="submit" value="Submit">
</form>

Here is the Process file for data processing.

<?php
     if ($_FILES["file"]["error"] > 0) {
           echo "Error: " . $_FILES["file"]["error"] . "<br>";
     } else {
           echo "Upload: " . $_FILES["file"]["name"] . "<br>";
           echo "Type: " . $_FILES["file"]["type"] . "<br>";
           echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
           echo "Stored in: " . $_FILES["file"]["tmp_name"];
     }
?>
php files super global variable

Here is the result page

php files super global variable

PHP $_COOKIE

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

<?php
     $value = 'something from somewhere';
     setcookie("TestCookie", $value);
     setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
     setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "http://localhost/roshni/test.php", 1);
?>

You can also delete cookie

<?php
     // set the expiration date to one hour ago
     setcookie ("TestCookie", "", time() - 3600);
     setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "http://localhost/roshni/test.php", 1);
?>

PHP $_SESSION

A PHP session variable is used to store information about, or change settings for a user session. When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end.

<?php session_start(); $_SESSION['views']=1;?>
<html>
     <body>
       <?php
            //retrieve session data
            echo "Pageviews=". $_SESSION['views'];
       ?>
     </body>
</html>

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php
      if(isset($_SESSION['views']))
        unset($_SESSION['views']);
?>

Summary of PHP Super Global Variables

The purpose of this article is to give the reader a brief overview on PHP Super Global Variables. In his article I have explained you PHP Super Global Variables and pretty much about PHP working areas.  

Hopefully this article helps to make it easy for you to work with PHP Super Global Variables.

About Author

Hi, I am Roshni Sharma. I am pursuing my Web Developer Master Course from ADMEC Multimedia Institute, Rohini, Delhi, India. Now I am studying PHP so that I have explained you some PHP Super Globals in this article.

Hope you like my article. For any query you can comment here. I’ll answer you asap.

Similar PHP Posts to read:

Leave a Reply

You must be logged in to post a comment.

Copy link