Learn PHP in One Day and Learn It Well

PHP for Beginners with Hands-on Project. The only book you need to start coding in PHP immediately. By Jamie Chan

Chapter 8: PHP Superglobals

We’ve covered a lot in the preceding chapters. Most of the topics covered so far are fundamental concepts common to other programming languages. In this chapter, we are going to learn something specific to PHP – PHP superglobals.

We’ll learn to use these superglobals to interact with HTML forms and pass information from one PHP script to another.

8.1 PHP Form Handling

First and foremost, this topic requires you to have a basic understanding of HTML form elements. If you are not familiar,https://www.w3schools.com/html/html_form_elements.aspprovides a quick reference that you can refer to.

If you are familiar, let’s start by creating a simple HTML form to work with later.

Open Brackets and create a new file called form.php in your htdocs folder. Add the following code to it:

<!DOCTYPE html>
<html>
<head>
<title>PHP Form Handling</title>
</head>
<body>
 <form action = "" method = "get">
 	Enter Name <BR>
	<input type = "text" name = "studentname" value = "Your Name">
	<BR><BR>
	Favorite Subject(s)<BR>
 	<input type = "checkbox" name = "subj[]" value = "EL">English
	<input type = "checkbox" name = "subj[]" value = "MA">Math
	<input type = "checkbox" name = "subj[]" value = "PG">Programming
	<BR><BR>
	Gender <BR>	<input type = "radio" name = "gender" value = "M">Male
	<input type = "radio" name = "gender" value = "F">Female
	<BR><BR>
 	<input type = "submit" name="sm" value = "Submit Form">
 </form>
</body>
</html>

Study the code above carefully. Notice that we use the following <form> tag to create a HTML form?

<form action = "" method = "get">

This tag has two attributes – action and method .

The action attribute specifies the file that we want to use to process the HTML form. In our example, we assign an empty string to it. This means that we want to use the current file (i.e., form.php) to process the form.

If we want to use a different file to process the form, we need to assign the path of that file to the action attribute. For instance, suppose we want to use process.php and process.php is in the same folder as form.php, we need to write

<form action = "process.php" method = "get">

Next, we have the method attribute. This attribute specifies the method that we want to use to send the form data. There are two methods available: get and post . If we do not specify any method, the default is get . In our example, we specify that we want to use the get method. We’ll discuss both methods later.

Next, let’s look at the <input> tags in our form; these tags are used to create various form elements.

Notice that all <input> tags have a name attribute? This attribute is used to name the respective form elements. For instance, the first form element (which is a text box) is named “studentname”, as shown in the code below:

<input type = "text" name = "studentname" value = "Your Name">

It is mandatory for us to name form elements if we want to use PHP to process those elements. Similar to how variables in PHP have names, all form elements must have a name so that we can reference them in our code later.

Next, notice that all checkboxes ( type = "checkbox" ) in our form are named “subj” and both radio buttons ( type = "radio" ) are named “gender”?

Both radio buttons have the same name as they belong to the same group (i.e., they are both options for “Gender”).

Similarly, the three checkboxes have the same name as they are all options for “Favorite Subject(s)”.  As users can choose more than one option for checkboxes, we need to add a pair of square brackets to indicate that the option(s) selected will be stored as an array.

Last but not least, notice that all <input> tags have a value attribute? This attribute behaves differently depending on the form element. For text boxes, it specifies the initial value displayed in the box. For “submit” buttons, it specifies the text on the button.

For checkboxes, radio buttons and drop down lists, it specifies the value that will be submitted for each selected option. For instance, if the following checkbox is selected

<input type = "checkbox" name = "subj[]" value = "EL">English

the string "EL" will be submitted to the PHP server, as we assigned "EL" to its value attribute.

Got it? Great! Let’s move on to discuss the isset() function.

8.1.1 The isset() function

The isset() function is an important function that is commonly used in PHP form handling. This function checks if a variable has been declared and is not NULL .

 NULL is a special value that, ironically, is used to indicate that a variable has no value.

Suppose we have two variables $a and $b as shown below:

$a = 5;
$b = NULL;

The following statements

var_dump(isset($a));
var_dump(isset($b));
var_dump(isset($c));

give us

bool(true) bool(false) bool(false)

as the output.

 $a is considered set (i.e., isset($a) returns true ) as it has been declared and has a non NULL value. In contrast, $b and $c are both considered unset (i.e., isset($b) and isset($c) return false ) as $b has a NULL value and $c has not been declared.

The isset() function is commonly used to determine if a button has been clicked. We’ll learn to do that later.

Next, let’s talk about the get and post methods.

8.1.2 get and $_GET

Both the get and post methods can be used to send form data to the PHP server for processing. The main difference is that when the get method is used, form data is appended to the URL. In addition, there is a limit to the amount of data that can be transmicodeed using the get method.

The form in form.php currently uses the get method. Suppose we fill in the form with the following data:

When we click on the “Submit Form” button, the URL changes to http://localhost/form.php?studentname=Alex&subj%5B%5D=EL&subj%5B%5D=MA&gender=M&sm=Submit+Form

Notice the question mark ( ? ) in the URL? This question mark is used as a separator; what follows the question mark in the URL is known as a query string.

The query string contains the form data that we submitted, with each data presented as a name=value pair, separated by ampersands ( & ).

For instance, as we entered the string “Alex” into the text field named “studentname”, the pair studentname=Alex gets appended to the URL.

Next, we selected the options “English” and “Math” for “Favorite Subject(s)”. Hence, the pairs

subj%5B%5D=EL&subj%5B%5D=MA

get appended to the URL. These pairs use URL encoding to encode special characters that cannot be displayed in an URL. %5B encodes the character “[” while %5D encodes “]”.

If you decode subj%5B%5D=EL&subj%5B%5D=MA you’ll get subj[]=EL&subj[]=MA

This indicates that we submitted the values “EL” and “MA” for the “subj” form element.

Now, suppose we want to use the information stored in the query string in our PHP scripts, how do we do that?

Simple. We use the $_GET superglobal. $_GET is a superglobal that stores the query string as an associative array.

To view all data in $_GET , we can use the print_r() function. To see how that works, add the following lines of code to form.php, between the </form> and </body> tags:

<?php
	if (isset($_GET['sm']))
	print_r($_GET);
?>

Here, we use the isset() function to check if $_GET['sm'] is set. Before we click on the “Submit Form” button (named “sm”), $_GET['sm'] is considered to be unset.

When we click on the button, PHP assigns the string 'Submit Form' to $_GET['sm'] and the variable becomes set.

When that happens, isset($_GET['sm']) returns true and the if block is executed.

Reload form.php (without the query string) and enter the same data we entered previously into the form. Next, click on the “Submit Form” button; you’ll see the following line appended to the bocodeom of the page:

Array ( [studentname] => Alex [subj] => Array ( [0] => EL [1] => MA ) [gender] => M [sm] => Submit Form )

This gives us the content of the $_GET[] array.

In other words, $_GET['studentname'] = 'Alex'$_GET['subj'] = array('EL', 'MA')$_GET['gender'] = 'M' and $_GET['sm'] = 'Submit Form' .

Got it? Great! Let’s move on to the post method now.

8.1.3 post and $_POST

The post method is similar to the get method, except that form data is not appended to the URL. This makes the post method suitable for sending sensitive information to the server, as information will not be visible in the URL.

Let’s look at an example. Change the line

<form action = "" method = "get">

in form.php to

<form action = "" method = "post">

Next, change the PHP code to

if (isset($_POST['sm']))
	print_r($_POST);

Finally, load form.php again without any query string and enter the same data we entered previously into the form. Click on the ‘Submit Form’ button.

You should see the URL in your address bar remains unchanged. Other than that, everything else is the same. In other words, you’ll get the same output appended to the bocodeom of the form.

Processing a form using the get vs post method is very similar. The main difference is one appends a query string to the URL while the other doesn’t. In addition, with the get method, we use the $_GET superglobal. With the post method, we use the $_POST superglobal. Clear?

8.1.4 Keeping The Values in The Form

In the previous sections, we learned to process HTML forms using the get and post methods.

Regardless of which method we use, notice that whenever we click on the “Submit Form” button, the form refreshes itself and data entered is not shown on the form anymore?

This is all right if the form is processed successfully. However, if the form is not processed successfully and we need users to resubmit the form, this can be very troublesome as users need to fill out all the fields again. If we do not want that to happen, we can use echo statements.

For text boxes, we use echo statements to modify the value attribute. This attribute allows us to prefill a text box with text. In form.php, we prefilled the text box with the text “Your Name”. Alternatively, we can use PHP to prefill the text box with user-entered data. To do that,

Change

<input type = "text" name = "studentname" value = "Your Name">

to

<input type = "text" name = "studentname" value = "<?php
 	if (isset($_POST['studentname']))
 		echo $_POST['studentname'];
?>">

If you analyze the code above carefully, you’ll notice that we replaced the text “Your Name” with the following block of PHP code:

<?php
 	if (isset($_POST['studentname']))
 	  echo $_POST['studentname']; 
?>

This code first checks if $_POST['studentname'] is set.

If it is (i.e., the user has submitted data for this text field previously), we use an echo statement to prefill the text box with the information submitted. Got it?

It is relatively straightforward to prefill a text box with user-entered data. Things get a bit more complicated when we want to prefill elements like checkboxes, radio buttons and drop down lists. To prefill these elements, we need to know which option has been selected and use PHP to select these options dynamically. Let’s look at an example using checkboxes.

A checkbox is selected when you add the word “checked” (without quotes) to its tag. For instance,

<input name = "subj[]" type = "checkbox" value = "EL" checked>English

results in the checkbox labelled “English” being selected. If we want PHP to dynamically select this checkbox, we need to replace the code above with:

<input type = "checkbox" name = "subj[]" value = "EL"
<?php
 	if (isset($_POST['subj']) && in_array('EL', $_POST['subj']))
 	  echo 'checked'; 
?>
>English

Here, we use PHP to check if $_POST['subj'] is set and if the current option is selected. If it is, the string 'EL' should be found in the $_POST['subj'] array. In other words, in_array('EL', $_POST['subj']) should return true .

If that’s the case, we echo 'checked' to select this checkbox. This dynamically selects the checkbox labelled “English”. Got it?

Great! We’ll be writing a function to prefill forms in our project later.

8.1.5 Filtering User Input

Next, let’s move on to discuss how we can filter user inputs in our forms. Filtering refers to the sanitization and validation of user inputs.

Sanitization is the process of removing invalid characters from the input. For instance, sanitizing an integer involves removing all characters except digits, plus and minus signs from the input.

Validation, on the other hand, is the process of checking if the input satisfies certain criteria. For instance, if the input is supposed to be an email address, we can use the validation process to check if it is indeed an email address (such as whether it contains the “@” character).

To filter user inputs, we use a built-in function called filter_var() . When using this function, we need to specify how we want to filter our inputs. We do that using one of the predefined filters found athttps://www.php.net/manual/en/filter.filters.php. Depending on the filter used, this function will either return the filtered data or return false .

For instance, if we want to remove invalid characters from an integer, we can use the FILTER_SANITIZE_NUMBER_INT filter as shown below:

$num = '12.5abc';
echo filter_var($num, FILTER_SANITIZE_NUMBER_INT);

If you run the code above, you’ll get 125 as the output.

If we want to validate whether an email address is valid, we can use the FILTER_VALIDATE_EMAIL filter. If we pass a valid email address to the function, it returns the email address. Else, it returns false . For instance,

$email = '[email protected]';
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));

gives us

bool(false)

as “[email protected]” is not a valid email address (“.com” is missing).

8.1.6 Cross-Site Scripting

Great! We’ve covered most of the form handling concepts in PHP. Last but not least, let’s move on to cross-site scripting. For this, I need to do a licodele demonstration.

Change the PHP code in form.php (between the </form> and </body> tags) to the following:

if (isset($_POST['studentname']))
	echo 'You entered '.$_POST['studentname'].' into the text field';

and reload the page. Type

<script>alert(‘Hacked’);</script>

into the text field and click on the “Submit Form” button. What do you get?

You get an alert box that says “Hacked” right?

Surprised?

This example demonstrates a critical security concept in PHP – cross-site scripting (also known as XSS).

Cross-site scripting occurs when a user enters undesirable scripting code into our PHP form and submits the code. If our site then stores this code (for instance, in a database) and displays it to another user, the malicious code will be executed in the other user’s browser.

In our example, we created a harmless alert box using Javascript. However, users with malicious intent can definitely use this same technique to run harmful scripting code on the victim’s browser.

To prevent this from happening, we need to be careful whenever we display information entered by users. There are a few ways to do it. The easiest is to use a built-in function called htmlspecialchars() . This function converts special characters into HTML entities.

Special characters refer to characters that have special significance in HTML, such as the < and > characters. If you do not want < and > to represent the start and end of an HTML tag, you need to encode them using the htmlspecialchars() function. This function converts < and > to < and > respectively.

 <script> will thus be converted to <script> and no longer interpreted as an HTML tag. To see how this works, change the PHP code above to

if (isset($_POST['studentname']))
	echo 'You entered '.htmlspecialchars($_POST['studentname']).' into the text field';

For demonstration purposes, we only encode the text field. In actual coding, you have to encode every form element where users are allowed to enter information themselves.

If you load the page and enter

<script>alert(‘Hacked’);</script>

into the text field now, you’ll see that the alert box no longer pops out when you submit the form. Instead, you get the following output below the form:

You entered <script>alert('Hacked');</script> into the text field.

 <script> and </script> are treated as normal text with no HTML significance.

If you right-click on your webpage and select “View Page Source”, you’ll see the line

You entered <script>alert('Hacked');</script> into the text field.

below the </form> tag. This shows the encoding of the < and > characters.

8.2 $_SESSION

We’ve covered quite a bit in this chapter so far. In the previous section on PHP form handling, you learned about the $_GET and $_POST superglobals. In this section, we are going to discuss another superglobal – $_SESSION .

In PHP, a session is a way of storing information that can be accessed across multiple pages; this information is stored in the $_SESSION superglobal.

Like the $_GET and $_POST superglobals, the $_SESSION superglobal is an associative array. This array is stored on the server and is available to all pages on the site during the duration of the session.

To demonstrate the use of sessions, we need to create two pages, session.php and session2.php. Let’s do that now.

First, create a new file called session.php in htdocs and add the following code to it (line numbers are added for reference).

1  <?php
2 	session_start();
3
4 	$_SESSION['myFavFood'] = 'Pizza';
5 	$_SESSION['myFavDrink'] = 'Cola';  
6 	$_SESSION['myFavColor'] = 'Orange';
7
8 	#updating a session variable
9 	$_SESSION['myFavDrink'] = 'Beer';
10
11 	#deleting a session variable
12 	unset($_SESSION['myFavColor']);

Here, we use a built-in function called session_start() to start a new session on line 2. This function creates a new session if one has not already been created or resumes the current one if it exists. Each session created is associated with an automatically generated unique session ID.

After creating the session, we store the strings 'Pizza''Cola' and 'Orange' into the $_SESSION superglobal, using 'myFavFood''myFavDrink' and 'myFavColor' as the keys respectively.

Next, we update the value of $_SESSION['myFavDrink'] by assigning a new string to it on line 9.

Finally, on line 12, we use another built-in function called unset() to destroy an element in the $_SESSION superglobal. To use this function, we pass the name of the element that we want to destroy to the function. After the element is destroyed, we will no longer be able to access it.

Next, let’s create another file called session2.php (in htdocs) and add the following code to it:

<?php
	session_start();
	echo '<BR>Food: '.$_SESSION['myFavFood'];
	echo '<BR>Drink: '.$_SESSION['myFavDrink'];
	echo 'Color: '.$_SESSION['myFavColor'];

Here, we start by calling the session_start() function to resume the current session. We need to call this function whenever we want to access the $_SESSION superglobal.

Next, we use three echo statements to output the values stored in $_SESSION .

Now, we are ready to demonstrate how sessions work.

To do that, load session.php in your browser first. When you do that, session.php starts a new session and stores data into the $_SESSION superglobal.

Next, load session2.php in your browser. What do you get? Depending on the error setting on your PHP server, you will get an output similar to what is shown below:

Food: Pizza
Drink: Beer
Notice: Undefined index: myFavColor in …session2.php on line 6
Color:

Notice that we get an undefined index notice for “myFavColor”? This is because $_SESSION['myFavColor'] was destroyed using the unset() function in session.php.

Other than that, we have successfully retrieved the values of $_SESSION['myFavFood'] and $_SESSION['myFavDrink'] . These two values were stored in the $_SESSION superglobal in session.php and retrieved in session2.php.

This demonstrates how we can use the $_SESSION superglobal to store and retrieve data across different PHP pages. Got it?

Besides creating and storing data in a session, we can destroy a session. We commonly do that when users log out of our site. To destroy a session, we use another built-in function called session_destroy() .

To see how this function works, create a new file called session3.php in htdocs and add the following code to it:

<?php
	session_start();
	session_destroy();

As shown in the code above, we need to call the session_start() function to resume an existing session before destroying it.

Next, load session3.php in your browser; this destroys the current session.

Finally, load session2.php in your browser again. You’ll get an output that says indexes “myFavFood”, “myFavDrink” and “myFavColor” are all undefined. This indicates that the session no longer exists.

8.3 $_COOKIE

Cool! We’ve come to the final topic in this chapter – cookies.

A cookie is another way of storing information that can be accessed across multiple pages on the site. It is essentially a small text file that stores data on the user’s computer (as opposed to a session that stores data on the server).

As cookies are stored on the user’s computer, you should not use cookies to store sensitive data, as a malicious user could potentially manipulate it. Also, cookies may be disabled on the user’s browser. Hence, if the information to be stored is crucial or sensitive, you should use sessions instead.

To create a cookie, we use the set_cookie() function.

Similar to the header() function covered in Chapter 3.3, the set_cookie() function must be called before your script generates any output. If you fail to do that, you’ll get a “Cannot modify header information – headers already sent” warning and the cookie will not be set. Your code may work when you are working on your local computer, but when you upload it to your hosting company’s server, it will fail to work.

The set_cookie() function accepts up to seven arguments; only the first is mandatory. We commonly provide the first three arguments to the function, namely the name of the cookie, the value of the cookie and the expiry date in UNIX timestamp format.

Let’s look at an example. Create a file called cookie.php in htdocs and add the following code to it:

<?php
 setcookie('userName', 'Joy', time() + 120);
 #modifying a cookie
 setcookie('userAge', 25, time() + 3600);
 setcookie('userAge', 26, time() + 3600);
 #deleting a cookie
 setcookie('userLevel', 3, time() + 3600);
 setcookie('userLevel', 3, time() - 3600);

Here, we set three cookies – userNameuserAge and userLevel .

For the first cookie ( userName ), its value and expiry date are 'Joy' and time() + 120 respectively.

 time() is a built-in function that gives us the current Unix timestamp; time() + 120 means the cookie will expire 120 seconds (i.e. 2 minutes) after it is set.

Next, we have the userAge cookie. This cookie is set twice. When a cookie is set more than once, the newest cookie overwrites the previous ones. Hence, the value of userAge is updated from 25 to 26 .

Finally, we have the userLevel cookie. This cookie is set with an initial expiry of time() + 3600 . However, it is subsequently updated to an expiry of time() - 3600 . When a cookie has an expiry in the past, it gets deleted.

Let’s look at how we can access each of these cookies now. We do that using the $_COOKIE superglobal. Create another file called cookie2.php in htdocs and add the following code to it:

<?php
 	echo 'User Name is '.$_COOKIE['userName'];
	echo '<BR>User Age is '.$_COOKIE['userAge'];
	echo 'User Level is '.$_COOKIE['userLevel'];

We are now ready to test our scripts. First, launch cookie.php in your browser. When you do that, the three cookies ( userNameuserAge and userLevel ) get created.

Next, launch cookie2.php. Depending on the error setting on your PHP server, you’ll get an output similar to what is shown below:

User Name is Joy
User Age is 26
Notice: Undefined index: userLevel in ...cookie2.php on line 4
User Level is

The userLevel cookie does not exist as it has been deleted. Wait 2 minutes and reload cookie2.php. You’ll get an output similar to the following:

Notice: Undefined index: userName in ...cookie2.php on line 2
User Name is
User Age is 26
Notice: Undefined index: userLevel in ...cookie2.php on line 4
User Level is

The userName cookie is also non-existent now as it has expired.