php superglobals


Superglobals are predefined variables in PHP and are always accessible regardless of scope. You 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

$GLOBALS

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

Example

$x = 75; 
$y = 25;

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

addition(); 
echo $z;   

$_SERVER

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

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'];  

$_REQUEST

$_REQUEST is used to collect data after submitting an HTML form. When a user submits the data by clicking Submit button, the form data is sent to the file specified in the action attribute of the <form> tag. We can use the super global variable $_REQUEST to collect the value of the input field. $_REQUEST can retrieve values from $_POST, $_GET and $_COOKIE.

<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;
	}
}
?>  

$_POST

$_POST is used when retrieving data from a form securely.

<form method="POST">
	<input type="name" name="name">
	<input type="email" name="email">
	<input type="password" name="password">
	<input type="submit" name="submit" value="POST">
</form>

Action attribute is not required if the data is processed in the same file. Default method of sending data is GET so, we need to specify the method in form if we need to send it using post method. Input name serves as a key to the value for data that is sent as associative array.

<?php 
print_r($_POST);
?>

This will print the values in array.

To access individual values from S_POST.

$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

echo 'Welcome Mr. '.$name .'. Your email is' .$email .' and your password is '.$password.;

These lines of codes will working fine once you have data in $_POST but it'll display errors when the page is loaded for the first time as there won't be any data in S_POST. So, it's good to check if there is data in $_POST or not before executing those codes. Then, the codes will run only if there's any data that come from post method.

if(!empty($_POST)){
	$name = $_POST['name'];
	$email = $_POST['email'];
	$password = $_POST['password'];

	echo 'Welcome Mr. '.$name .'. Your email is' .$email .' and your password is '.$password.;
}

We can even check if the request method is post or not.

if(!empty($_POST) && $_SERVER[''REQUEST_METHOD'] === 'POST'){
	$name = $_POST['name'];
	$email = $_POST['email'];
	$password = $_POST['password'];

	echo 'Welcome Mr. '.$name .'. Your email is' .$email .' and your password is '.$password.;
}

$_GET

Form method get transfers the data via url. So, it's insecured to pass data values from get method. so we use post method while working on data.

$name = hari;
$age = 33; 

<a href="page.php?name=<?=$name?>&age=<?=$age?>">Click Me</a>

This is a demo how the data is transferred via url query string using get method. & is used to separate the values in such cases. If we've got characters such as & in our values then we need to use urlencode() function to encode such characters in url. Such characters will be retained in the view file as they were. If not, we can use urldecode() function to retrieve those values after being decoded.

$name = hari&hari;
$age = 33;
<a href="page.php?name=<?=urlencode($name)?>&age=<?=urlencode($age)?>">Click Me</a>

POST vs GET

GET vs. POST

Both GET and POST create an array. This array holds key/value pairs where keys are the names of the form controls and values are the input data from the user. Both GET and POST are treated as $_GET and $_POST. $_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone as all the variables are displayed in the URL. GET also has character limits of 2000 on the amount of information to send. Since the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. GET may be used for sending non-sensitive data.

When to use POST?

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. Since the variables are not displayed in the URL, it is not possible to bookmark the page.

$_SESSION

Session values are stored in the server and can be retrieved anywhere in the server. To retrieve a value from session, session must be started first using php inbuilt session_start() function. Lets set some values in session.

session_start();
$_SESSION['name'] = "John";
$_SESSION['email'] = "John@gmail.com";

Now, you can go to any of your files and retrieve those values.

session_start();
print_r($_SESSION);

You can unset any set values in session using unset().

unset($_SESSION['name']);

To delete all values from session we can use session_destroy() function.

session_destroy();

$_COOKIE

Cookie values are stored in users browser and are accessed through the browser. The user has the priviledge to destroy such cookies. Cookies can be set using setcookie() function with the cookie name and value along with its expiry time.

setcookie('name','john',(time()+120));
setcookie('email','john@gmail.com',(time()+120));

Here, time() + 120 means the cookie's expiry time is 2 minuste or 120 seconds after current time.

We can view the set cookies by opening browser settings -> advanced settings -> content settings -> cookie and site data.

To access cookie in view files we can use print_r($_COOKIE)

To destroy a cookie we can use setcookie function itself with current time or expired timestamp in the time parameter.

setcookie('name','john',1);

S_FILES

$_FILES contains all the informations about files being uploaded via POST method as an associative array.

[upload] => Array
	(
		[name] => filename.extension
		[type] => filetype
		[tmp_name] => temporary location of file
		[error] => error number
		[size] => file size in bytes
	)

Once a file is uploaded, informations regarding the name of file, file type, temporary location of the uploaded file, error index and the size of file are sent to the php server. There are 7 types of error related to file uploads numbered as 0 - 8 excluding number 5. let's have a overview of them first.

0 UPLOAD_ERR_OK -> file upload sucessful

1 UPLOAD_ERR_INI_SIZE -> file size larger than maximum filesize allowed to upload by server (php.ini in local server term(UPLOAD_MAX_FILESIZE))

2 UPLOAD_ERR_FORM_SIZE -> max file size => validation using input type hidden name MAX_FILE_SIZE value in bytes on top of the input fields

3 UPLOAD_ERR_PARTIAL -> partial upload

4 UPLOAD_ERR_NO_FILE -> no file

6 UPLOAD_ERR_TMP_DIR -> no temporary directory

7 UPLOAD_ERR_CANT_WRITE -> can't write to disk due to file/folder permissions issue

8 UPLOAD_ERR_EXTENSION -> file upload prevented due to extension => extension validation

We need to use those informations to upload that file. At first, we need to hold the required informations in some variables. Then, we can use move_uploaded_file() function to move the file to desired directory. We'll go through details about file uploads in next lesson.

<?php
if(!empty($_FILES)){
	$name = $_FILES['upload']['name'];
	$tmpName = $_FILES['upload']['tmp_name'];
	$error = $_FILES['upload']['error'];

	// create folder path
	$path = "Uploads/".$name;

	if($error == 0){
		move_uploaded_file($tmpName, $path);
	}else{
		echo 'Unable to upload.';
	}
}
?>	

$_ENV

$_ENV contains environment variables, mainly containing information about your server, paths, etc.