[go: up one dir, main page]

0% found this document useful (0 votes)
184 views11 pages

Super Global Variables

Superglobals were introduced in PHP 4.1.0 and allow variables to be accessed globally without needing to declare them globally. The document discusses the various PHP superglobal variables like $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, and $_SESSION that are automatically available in all scopes. It provides examples of how to use each superglobal variable to collect form data, retrieve header information, and manage sessions and cookies across PHP pages.

Uploaded by

Isha Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views11 pages

Super Global Variables

Superglobals were introduced in PHP 4.1.0 and allow variables to be accessed globally without needing to declare them globally. The document discusses the various PHP superglobal variables like $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, and $_SESSION that are automatically available in all scopes. It provides examples of how to use each superglobal variable to collect form data, retrieve header information, and manage sessions and cookies across PHP pages.

Uploaded by

Isha Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Superglobals were introduced in PHP 4.1.

PHP Global Variables - Superglobals


Some predefined variables in PHP are "superglobals", which means that they are
always accessible, regardless of scope - and we can access them from any function,
class or file without having to do anything special.

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 (also from within functions or methods).

PHP stores all global variables in an array called $GLOBALS [index]. The index holds
the name of the variable.

The example below shows how to use the super global variable $GLOBALS:

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

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>

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

The example below shows how to use some of the elements in $_SERVER:

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

PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after
submitting an HTML form.

The 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 this
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 $_REQUEST to collect the value of the input field:
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 = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="post". $_POST is also widely used to pass
variables.

The 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:

Example
<html>
<body>
<form method="post" action= ”abc.php”>
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>

PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="get".

$_GET can also collect data sent in the URL.

Assume we have an HTML page that contains a hyperlink with parameters:

<html>
<body>

<a href="update_get.php?std_id=$row[‘sno’]&email=$row[‘email’]">Update</a>

</body>
</html>

PHP Session
PHP session is used to store and pass information from one page to another temporarily (until
user close the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to
another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.

PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set and
get session variable values. Session variables are set with the PHP global variable:
$_SESSION.

PHP session_start() function


PHP session_start() function is used to start the session. It starts a new or resumes existing session.
It returns existing session if session is created already. If session is not available, it creates and
returns new session.

Start a PHP Session


A session is started with the session_start() function.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["username"] = "abc";
$_SESSION["email"] = "abc@yahoo.com";
echo "Session variables are set.";
?>

</body>
</html>

Get PHP Session Variable Values


Notice that session variables are not passed individually to each new page, instead
they are retrieved from the session we open at the beginning of each page
(session_start()).

Also notice that all session variable values are stored in the global $_SESSION
variable:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

Another way to show all the session variable values for a user session is to run the
following code:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

PHP Session Counter Example


File: sessioncounter.php

1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>
Modify a PHP Session Variable
To change a session variable, just overwrite it:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session,
use session_unset() and session_destroy():

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize
the user.

Cookie is created at server side and saved to client browser. Each time when client sends request
to the server, cookie is embedded with request. Such way, cookie can be received at the server
side.

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

PHP setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can
access it by $_COOKIE superglobal variable.

1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Example

1. setcookie("CookieName", "CookieValue");/* defining name and value only*/


2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*6
0 seconds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com",
1);

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Example

1. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example


File: cookie1.php
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.

1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>
Reference: https://www.javatpoint.com/

You might also like