"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Monday, June 11, 2018

PHP SUPER GLOBAL VARIABLE

What is super global variable ?
Super global were introduced to PHP of version 4.0 and higher.
These are specially-defined array variables in PHP that make it easy for you to get information about a request or its context.
Superglobals are built-in variables that are always available in all scopes
The superglobals are available throughout your script. These variables can be accessed from any function, class or any file without doing any special task such as declaring any global variable etc.
They are mainly used to store and get information from one page to another etc in an application.
the PHP Superglobals represent data coming from URLs, HTML forms, cookies, sessions, and the Web server itself.
Types of super global variables:
The PHP super global variables are:
1.      $GLOBALS
2.      $_SERVER
3.      $_REQUEST
4.      $_POST
5.      $_GET
6.      $_FILES
7.      $_ENV
8.      $_COOKIE
9.      $_SESSION

1.PHP $GLOBALS:

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script means also from within functions or methods.
PHP stores all global variables in an array called $GLOBALS[index]. Where the index holds the name of the variable.

Example:

<?php
$x = 75;
$y = 25;

function substraction() {
    $GLOBALS['z'] = $GLOBALS['x'] - $GLOBALS['y'];
}

substraction ();
echo $z;
?>
Output:
50
Example2:
<?php
$x = 300;
$y = 200;
function addition (){
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
Output:
500

In the above code two global variables are declared $x and $y which are assigned some value to them. Then a function addition() is defined to add the values of $x and $y and store in another variable $z defined in the GLOBAL array.

2.$_SERVER:

It is a PHP super global variable that stores the information about headers, paths and script locations.

Some of these elements are used to get the information from the superglobal variable $_SERVER.

Example:


<?php


echo $_SERVER['PHP_SELF'];


echo "<br>";


echo $_SERVER['SERVER_NAME'];


echo "<br>";


echo $_SERVER['HTTP_HOST'];


echo "<br>";


echo $_SERVER['HTTP_USER_AGENT'];


echo "<br>";


echo $_SERVER['HTTP_REFERER'];
echo "<br>";


echo $_SERVER['SCRIPT_NAME'];


echo "<br>"


?>


In the above code we used the $_SERVER elements to get some information. We get the current file name which is worked on using ‘PHP_SELF’ element. Then we get server name used currently using ‘SERVER_NAME’ element. And then we get the host name through ‘HTTP_HOST’.

Elements that can use inside $_SERVER:
Sl.No.
Elements
Description
1
$_SERVER['PHP_SELF']

Returns the filename of the currently executing script
2
$_SERVER['GATEWAY_INTERFACE']
Returns the version of the Common Gateway Interface (CGI) the server is using
3
$_SERVER['SERVER_ADDR']
Returns the IP address of the host server
4
$_SERVER['SERVER_NAME']
Returns the name of the host server
5
$_SERVER['SERVER_SOFTWARE']
Returns the server identification string (such as Apache/2.2.24)
6
$_SERVER['SERVER_PROTOCOL']
Returns the name and revision of the information protocol (such as HTTP/1.1)
7
$_SERVER['REQUEST_METHOD']
Returns the request method used to access the page (such as POST)
8
$_SERVER['REQUEST_TIME']
Returns the timestamp of the start of the request (such as 1377687496)
9
$_SERVER['QUERY_STRING']
Returns the query string if the page is accessed via a query string
10
$_SERVER['HTTP_ACCEPT']
Returns the Accept header from the current request
11
$_SERVER['HTTP_HOST']
Returns the Host header from the current request
12
$_SERVER['HTTP_ACCEPT_CHARSET']
Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
13
$_SERVER['HTTP_REFERER']
Returns the complete URL of the current page (not reliable because not all user-agents support it)
14
$_SERVER['HTTPS']
Is the script queried through a secure HTTP protocol
15
$_SERVER['REMOTE_ADDR']
Returns the IP address from where the user is viewing the current page
16
$_SERVER['REMOTE_HOST']
Returns the Host name from where the user is viewing the current page
17
$_SERVER['REMOTE_PORT']
Returns the port being used on the user's machine to communicate with the web server
18
$_SERVER['SCRIPT_FILENAME']
Returns the absolute pathname of the currently executing script
19
$_SERVER[SERVER_ADMIN']
Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as someone@w3schools.com)
20
$_SERVER[SERVER_PORT']
Returns the port on the server machine being used by the web server for communication (such as 80)
21
$_SERVER[SERVER_SIGNATURE']
Returns the server version and virtual host name which are added to server-generated pages
22
$_SERVER[PATH_TRANSLATED']
Returns the file system based path to the current script
23
$_SERVER[SCRIPT_NAME']
Returns the path of the current script
24
$_SERVER[SCRIPT_URI']
Returns the URI of the current page

3.PHP $_REQUEST

PHP $_REQUEST is a superglobal variable which is used to collect the data after submitting a HTML form.But  $_REQUEST is not used mostly.

Example:


<!DOCTYPE html>


<html>


<body>


<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


 NAME: <input type="text" name="fname">


 <button type="submit">SUBMIT</button>


</form>


<?php


if ($_SERVER["REQUEST_METHOD"] == "POST") {


    $name = htmlspecialchars($_REQUEST['fname']);


    if(empty($name)){


        echo "Name is empty";


    } else {


        echo $name;


    }


}


?>


</body>


</html>


In the above code we have created a form that takes the name as input from the user and prints it’s name on clicking of submit button. We transport the data accepted in the form to the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we manipulate the data in the same page using the PHP code.

The data is retrieved using the $_REQUEST super global array variable.

4.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.
 It is a super global variable used to collect data from the HTML form after submitting the HTML form. When form uses method post to transfer data, the data is not visible in the query string, security levels are maintained in this method.
Example:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>
</body>
</html>
Here in this example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field.

5.PHP $_GET

PHP $_GET can also be used to collect form data after submitting an HTML form with method="get".
When form uses method get to transfer data, the data is visible in the query string, therefore the values are not hidden. $_GET super global array variable stores the values that come in the URL.
Example:
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>

5.PHP $_FILES

PHP $_FILES  is also a super global variable .
This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables −
·     $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
·      $_FILES['file']['name'] − the actual name of the uploaded file.
·      $_FILES['file']['size'] − the size in bytes of the uploaded file.
·     $_FILES['file']['type'] − the MIME type of the uploaded file.
·     $_FILES['file']['error'] − the error code associated with this file upload.
Example:

<?php
    $currentDir = getcwd();
    $uploadDirectory = "/uploads/";

    $errors = []; // Store all foreseen and unforseen errors here

    $fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions

    $fileName = $_FILES['myfile']['name'];
    $fileSize = $_FILES['myfile']['size'];
    $fileTmpName  = $_FILES['myfile']['tmp_name'];
    $fileType = $_FILES['myfile']['type'];
    $fileExtension = strtolower(end(explode('.',$fileName)));

    $uploadPath = $currentDir . $uploadDirectory . basename($fileName);

    if (isset($_POST['submit'])) {

        if (! in_array($fileExtension,$fileExtensions)) {
            $errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
        }

        if ($fileSize > 2000000) {
            $errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
        }

        if (empty($errors)) {
            $didUpload = move_uploaded_file($fileTmpName, $uploadPath);

            if ($didUpload) {
                echo "The file " . basename($fileName) . " has been uploaded";
            } else {
                echo "An error occurred somewhere. Try again or contact the admin";
            }
        } else {
            foreach ($errors as $error) {
                echo $error . "These are the errors" . "\n";
            }
        }
    }


?>


Look at the code above.
  1. ·         $fileName = $_FILES['myfile']['name']; This refers to the real name of the uploaded file.
  2. ·         $fileSize = $_FILES['myfile']['size']; This refers to the size of the file.
  3. ·         $fileTmpName = $_FILES['myfile']['tmp_name']; This is the temporary uploaded file that resides in the tmp/ directory of the web server.
  4. ·         $fileType = $_FILES['myfile']['type']; This refers to the type of the file. Is it a jpeg or png or mp3 file?
  5. ·         $fileExtension = strtolower(end(explode('.',$fileName))); This grabs the extension of the file.
  6. ·         $uploadPath = $currentDir . $uploadDirectory . basename($fileName); This is the path where the files will be stored on the server. We grabbed the current working directory.

7. $_ENV:
$_ENV is a superglobal that contains environment variables. Environment variables are provided by the shell under which PHP is running, so they may vary according to different shells.
To display an environment variable you can also use getenv()
Example:
<?php
   echo "<pre>";
   print_r($_ENV);
   echo "</pre>";
/* ****environment variables on a mac machine****
Array
(
[SHELL] => ***
[TMPDIR] => ***
[Apple_PubSub_Socket_Render] => ***
[USER] => ***
[SSH_AUTH_SOCK] => ***
[__CF_USER_TEXT_ENCODING] => ***
[PATH] => ***
[PWD] => ***
[HOME] => ***
[SHLVL] => ***
[DYLD_LIBRARY_PATH] => ***
[LOGNAME] => ***
[__LAUNCHD_FD] => ***
[DISPLAY] => ***
[_] => ***
[COMMAND_MODE] => ***
)
*/
?>
Example:
<?php
Echo ‘My username is’.$_ENV[“USER”].’!’;
?>

8.$_COOKIE Variable

$_COOKIE is used to create cookie.
Example:
<?php
$cookie_name=”user”;
$cookie_value=”Lopa”;
Setcookie($cookie_name,$ cookie_value,time() +(86400 * 30),”/”);

?>
<html>
<body>
<?php
If(!isset($_COOKIE[$cookie_name]))
{
echo “Cookie name ‘ “.$cookie_name.” ’is not set !”;
}
else
{
echo “Cookie name ‘ “.$cookie_name.” ’is set !”;
echo “Value is : “.$_COOKIE[$cookie_name];
}
?>
</body>
</html>

9.$_SESSION Variable

$_SESSION Variable is used to create session. It is a type of super global variable which is used to set the session variables.
Session variables contain data about the current user, and all pages contained in a single web application .

Example:
<?php
Session_start();
?>
<html>
<body>
<?php
$_SESSION[“favcolor”]=”green”;
$_SESSION[“favanimal”]=”cat”;
echo  “Session variable are set “;
?>
</body>
</html>
In addition to that the $_SESSION variable holds all of the session data declared in your files:


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template