© Gunnard Engebreth, Satej Kumar Sahu 2023
G. Engebreth, S. K. SahuPHP 8 Basicshttps://doi.org/10.1007/978-1-4842-8082-9_7

7. Sessions and Cookies

Gunnard Engebreth1   and Satej Kumar Sahu2
(1)
Madison, WI, USA
(2)
Bangalore, India
 

In the previous chapters, you learned how to use arrays, one of the most versatile and useful elements in PHP, to store multiple values within a single variable. Let’s now imagine you need to store some information to be used across multiple web pages. You need to store some information on a local computer (client side) or store some information on a server (server side) for just a certain time using the web page. How would you do this? By using sessions and cookies.

The main difference between sessions and cookies is that cookies, as previously said, are used to store some user information on a local computer as client-side files while sessions are server-side files that store user information on a web server.

While cookies expire right after the specified lifetime you define, sessions end when you close the web browser or when you log out of the web page or program.

This chapter consists of the following sections:
  • PHP Sessions

  • PHP Cookies

PHP Sessions

Sessions are what PHP uses to keep track of your activity on applications. For example, when you log into an application, make some changes, upload some images, and then leave the site, that’s a session. The application knows who you are and has been passing around and keeping track of a variable ($_SESSION) the whole time. Session variables hold information about individual users and are passed around the application to keep track of user activity.

Unlike normal variables, sessions need to be initiated in order to maintain integrity. To do this, PHP has a session_start() function. After this, session variables are set with the $_SESSION global variable.

Let’s make a simple page with a basic session declaration. Open the chapter7 folder and the first_session.php file.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["firstname"] = "Foo";
$_SESSION["username"] = "barFoo";
echo "Session variables are set.";
?>
</body>
</html>

So, session data has been set, but where is it? Sessions are stored on the server side so you can’t view them through methods such as inspect element. You can, however, use var_dump() to ensure that they are stored correctly.

Go browse back to chapter7 and open first_session2.php.

Great! So now you are saving session variables. For the real test, go back to chapter7 and find session_test.php. If you can open up a brand new page and still recall the session data, then you have success. All you need to do in session_test.php is use the start_session() function to access the session data. Go ahead and click session_test.php to view the data.

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

And for your last trick, let’s view the session variables and then destroy them! This will remove the session information that is currently active from the use of session_start().

Click remove_session.php in the chapter7 directory to view and remove the session data. Here is what remove_session.php looks like:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Here are the variables:<br />";
var_dump($_SESSION);
echo "<br /><br />";
// remove all session variables
session_unset();
echo "Here are the variables after session_unset:<br />";
var_dump($_SESSION);
echo "<br /><br />";
// destroy the session
session_destroy();
echo "Here are the variables after session_destroy:<br />";
var_dump($_SESSION);
echo "<br /><br />";
?>
</body>
</html>
Let’s take this concept and put it into a real-life situation, like a login page connected to a database. http://localhost/chapter7/ will show you a file called seedDB.php. Go ahead and click it. You will use this file to seed your database with some information. If all is working properly, you should see output in your browser that shows
Seeing Users into table..1..2..3
Users added
1 - tom - hanks - 1234 - 2022-04-15 17:39:21
2 - billy - mitchell - 1234 - 2022-04-15 17:39:21
3 - mega - man - 1234 - 2022-04-15 17:39:21
This is the test data you can use for this example. Open up login.php and take a look at the code.
<?php
// to Start a PHP session
session_start();
?>
<html>
<body>
     <div class="container">
               <form method="post" action="">
                    <div id="div_login">
                              <h1>Login</h1>
                              <div>
                                   <input type="text" class="textbox" id="first_name" name="first_name" placeholder="first_name" />
                              </div>
                              <div>
                                   <input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
                              </div>
                              <div>
                                   <input type="submit" value="Submit" name="submit" id="submit" />
                              </div>
                    </div>
               </form>
     </div>
<?php
// DB Host name
$host = "mysql-db";
// DB User
$user = "user";
// DB Password
$password = "pass";
// Database name
$db = "beginningPHP";
$connection = mysqli_connect($host, $user, $password, $db);
// If the connection fails
if (!$connection) {
     // Display message and terminate script
     die("Connection failed: " . mysqli_connect_error());
}
// If the submit button is pressed
if(isset($_POST['submit'])){
     // Escape special characters in a string
          $first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
          $password = mysqli_real_escape_string($connection, $_POST['password']);
     // If username and password are not empty
          if ($first_name != "" && $password != ""){
          // Query database to find user with matching username and password
               $query = "select count(*) as countUser from users where first_name='".$first_name."' and password='".$password."'";
          // Store query result
               $result = mysqli_query($connection, $query);
          // Fetch row as associative array
               $row = mysqli_fetch_array($result);
          // Get number of rows
               $count = $row['countUser'];
          // If number of row is more than zero
               if($count > 0){
               // Set matched user as current user
                         $_SESSION['first_name'] = $first_name;
                         $_SESSION['timestamp'] = date("h:i:sa");
               // Display success message
                    echo "You are logged in!";
                         if (isset($_SESSION)) {
                              echo "<br /><br />";
                              print_r($_SESSION);
                         }
          // Else if number of row is less than zero
               } else {
               // Display failed message
                         echo "Error! Invalid first_name and password.";
               }
          }
}
?>
</body>
</html>
Let’s break this down line by line.
<?php
// to Start a PHP session
session_start();
Here you are using the session_start() function to start your session.
?>
<html>
<body>
     <div class="container">
               <form method="post" action="">
                    <div id="div_login">
                              <h1>Login</h1>
                              <div>
                                   <input type="text" class="textbox" id="first_name" name="first_name" placeholder="first_name" />
                              </div>
                              <div>
                                   <input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
                              </div>
                              <div>
                                   <input type="submit" value="Submit" name="submit" id="submit" />
                              </div>
                    </div>
               </form>
This is your basic form that you will use to gather the credentials from your user. Use consistent naming with the database for easier tracking. This can be anything from “username”/“password” to “user”/“secret.”
     </div>
<?php
// DB Host name
$host = "mysql-db";
// DB User
$user = "user";
// DB Password
$password = "pass";
// Database name
$db = "beginningPHP";
$connection = mysqli_connect($host, $user, $password, $db);
This connects to your database using the credentials that will be used throughout this book. Below, you check for the connection and show an error if it fails for any reason:
// If the connection fails
if (!$connection) {
     // Display message and terminate script
     die("Connection failed: " . mysqli_connect_error());
}
// If the submit button is pressed
if(isset($_POST['submit'])){
     // Escape special characters in a string
          $first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
          $password = mysqli_real_escape_string($connection, $_POST['password']);
     // If username and password are not empty
          if ($first_name != "" && $password != ""){
You need to check the input and sanitize it before introducing it to the database. This will help prevent MySQL injection attacks.
               $query = "select count(*) as countUser from users where first_name='".$first_name."' and password='".$password."'";
Here is your query to check if the first_name value in the database is equal to $first_name from the form.
          // Store query result
               $result = mysqli_query($connection, $query);
           // Fetch row as associative array
               $row = mysqli_fetch_array($result);
           // Get number of rows
               $count = $row['countUser'];
           // If number of row is more than zero
               if($count > 0){
                // Set matched user as current user
                         $_SESSION['first_name'] = $first_name;
                         $_SESSION['timestamp'] = date("h:i:sa");
                // Display success message
                    echo "You are logged in!";
                         if (isset($_SESSION)) {
                              echo "<br /><br />";
                              print_r($_SESSION);
                         }
           // Else if number of row is less than zero
               } else {
               // Display failed message
                         echo "Error! Invalid first_name and password.";
               }
          }
}
?>
</body>
</html>

Use the test data “tom” and password “1234” to test. You can always go back to the chapter7 directory and run remove_session.php to clear out or log out the session data.

Please note that for preventing SQL injection you can use PDO (PHP data objects), which is an abstraction layer that can be used for database queries as an alternative to MySQLi.

PHP Cookies

Cookies are often used to identify a user. A cookie is a small file that is embedded on the user’s computer by the server. Remember that session variables are stored on the server, unlike cookies. Each time the same computer requests a page, the cookie is available for the application to read and identify the user. PHP can be used to both create and retrieve these cookie values.

Similar to sessions, you need to make use of a built-in PHP function named setcookie() to begin using them. The syntax for setting a cookie is
setcookie(name, value, expire, path, domain, secure, httponly);
Name is the only required value. Go a head and open first_cookie.php from chapter7 and look at the code.
<?php
$cookie_name = "username";
$cookie_value = "Betchy McCleaver";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
  echo "Cookie '" . $cookie_name . "' is set!<br>";
  echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

In this example, you are creating a cookie named username and setting the value to Betchy McCleaver (my eighth-grade science teacher). The expiration date of the cookie is 30 days. You come to this value by multiplying 86,400 (the total number of seconds in 24 hours/one day) by 30 (the length in days that you want the cookie to stay valid). Next, you set which part of your website can access the cookie: / , meaning any PHP application from the domain. To retrieve the cookie, much like $_SESSION, you use $_COOKIE.

Go to the chapter7 directory on your localhost in the browser and click first_cookie.php. You will see that it says the cookie is not set. This is because it is the first time you’ve run the script. Press refresh and you will see the cookie! You can verify the cookie through inspect element in your browser. Right-click the page and press inspect element and then click Application on the top right side and then Cookies on the left column, as shown in Figure 7-1.
Figure 7-1

Inspection element page to check on cookie information

Now let’s modify a cookie.

Open up modify_cookie.php. Change the value of username to Jason Bourne. You can verify this by refreshing the page or by the inspect element method above.

To delete a cookie, you basically invalidate the time. The cookie is created but set to a past date for expiration. This will invalidate and remove the cookie from your system.
<?php
// set the expiration date to one hour ago
setcookie("username", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

You can click delete_cookie.php for a working example of this.

A good habit to get into is to check if cookies are enabled before relying on them.
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
  echo "Cookies are enabled.";
} else {
  echo "Cookies are disabled.";
}
?>
</body>
</html>

Here you attempt to set an arbitrary cookie and then read it. If you can verify that the cookie is set, you know the user has cookies enabled!

Summary

In this chapter, you learned how to use sessions and cookies in the PHP language to keep track of your activity on web applications. You saw how to create, store, and manage information in PHP sessions and cookies.

In the next chapter, you will learn how to use PHP objects, which are another compound data type. They are similar to arrays, which can be set and used with multiple types of information, from strings to all types of numbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset