0% found this document useful (0 votes)
12 views23 pages

07.PHP Cookies and Sessions

The document provides an overview of PHP cookies and sessions, detailing how to create, access, and delete cookies using the setcookie() function and the $_COOKIE superglobal. It also explains session management, including starting sessions with session_start(), and simulating a user login process with session variables. Examples of code for setting cookies, managing sessions, and user authentication are included to illustrate the concepts.

Uploaded by

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

07.PHP Cookies and Sessions

The document provides an overview of PHP cookies and sessions, detailing how to create, access, and delete cookies using the setcookie() function and the $_COOKIE superglobal. It also explains session management, including starting sessions with session_start(), and simulating a user login process with session variables. Examples of code for setting cookies, managing sessions, and user authentication are included to illustrate the concepts.

Uploaded by

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

Server Side Internet

Programming
PHP Cookies and Sessions
Cookies
- Small file that server puts on computer to identify user
- Cookies help storing data and information to recognize an user
- Create cookies using setcookie() function
- Accessing cookies is like accessing associative array with the
superglobal: $_COOKIE
- IMPORTANT: always put this at the beginning of the file

Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Example: setting a cookie

<?php
// set cookie that expires after 2 days
setcookie("username", "john123", time() + 2 * 24 * 60 * 60);
?>
<!DOCTYPE html>
<html lang="en">
<body>
<?php
if (isset($_COOKIE["username"])) {
echo("<h1>Username is {$_COOKIE['username']}</h1>");
} else {
echo("<h1>No Cookie set</h1>");
}
?>
<p>Reload Page to see cookie!</p>
</body>
</html>
Delete a Cookie

- In order to delete a cookie, use the same function setcookie()


- Set the cookie value to empty and expiry date to less than 0 or using
time() - 60
- Need to refresh / close the browser in order to remove cookies
Example: deleting a cookie

<?php
// set cookie that expires after 2 days
setcookie("username", "john123", time() + 2 * 24 * 60 * 60);
setcookie("username", "", time() - 60);
?>
<!DOCTYPE html>
<html lang="en">
<body>
<?php
if (isset($_COOKIE["username"])) {
echo("<h1>Username is {$_COOKIE['username']}</h1>");
} else {
echo("<h1>No Cookie set</h1>");
}
?>
<p>Reload Page to see cookie!</p>
</body>
</html>
Session
- Information that is accessible via multiple pages
- Session is stored in the browser and server, so the application
knows the identity of the user no matter where the page is
- Session uses the PHP superglobal $_SESSION variable
- Session works like associative array
Functions in session

1. session_start() → Function to start session processing. Must be placed at


the beginning of the script before any HTML tags that need session!
2. session_unset() → removes all the session variables
3. session_destroy() → delete all existing sessions

Accessing session is easy, it is like accessing associative array, as an


example, we could set username in the session like:

$_SESSION["username"] = "computinguser";
$_SESSION["itemCount"] = 3;
And so on
Step by step
How do we simulate the login process?

1. Show login page with the form containing username and password
2. User clicks the login button and go to home page
3. In home page, check the session and login data. If not found, go
back to login
4. If data is found, check username and password
a. If session is not set, and data is correct: set session
b. Else, proceed as usual to show the data, because session is found
5. If the user clicks logout button/link, remove all sessions and redirect
to login
Example: Simulating user login process using session (login.php)

<!DOCTYPE html>
<html lang="en">
<body>
<form action="home.php" method="post">
<input type="text" name="username" placeholder="Username" required/>
<input type="password" name="password" placeholder="Password" required/>
<input type="submit" name="submit" value="Log In"/>
</form>
</body>
</html>
Example: home.php and contact.php

<?php
require("nav.php");
?>
<div> File: home.php
<h1>Home Page</h1>
</div>

<?php
require("nav.php");
?> File: contact.php
<div>
<h1>Contact Page</h1>
</div>
Example: helper function in function.php

<?php
function quit() {
header("Location: login.php", true, 303);
die();
}
?>

Note: check header() function


303. It means redirection for
HTTP request
Example: logout.php

<?php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
?>

Before logging out, make sure


to remove and destroy all
sessions in the user computer
and go to login.php
Example: nav.php
<?php
session_start();

require_once("function.php");

// check if not from submit or no session, quit


if (!isset($_POST["submit"]) and !isset($_SESSION["username"])) {
quit();
}

if (isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
if (!isset($_SESSION["username"]) and $username == "admin" and $password == "123") {
$_SESSION["username"] = $username;
} else {
quit();
}
}
?>
Example: nav.php (cont.)

<nav>
<a href="home.php">Home</a>
<a href="contact.php">Contact</a> Only show text and
<?php log out link if there is
if (isset($_SESSION["username"])) { a session
?>
<span>
<?php echo("Hello, {$_SESSION["username"]}"); ?>
</span>
<a href="logout.php">Log Out</a>
<?php
}
?>
</nav>
From the last slide
Notice the technique to call the logout.php file to simulate the logout
process. You could also use a function to do so, but most of the people
use the separate file or database table to store user data
Checking file for username and password
1. Create a file called as user.txt and put this inside: admin;123
2. Create a file called as Credential.php

We will use the Object-Oriented approach here


Example: Credential.php
<?php
class Credential {
private $file;
public $username;
public $password;
Notice we use OOP
function __construct() {
$this->file = fopen("user.txt", "r") or die("Unable to open file");
here
}

function __destruct() {
fclose($this->file);
}

function readFile() {
$info = fgets($this->file);
$infoArray = explode(";", $info);
$this->username = $infoArray[0];
$this->password = $infoArray[1];
}

function getUsername() {
return $this->username;
}

function getPassword() {
return $this->password;
}
}
?>
Example: nav.php with alternative to read user and password from a file
<?php
session_start();

require_once("function.php");
require_once("Credential.php");

// check if not from submit or no session, quit


if (!isset($_POST["submit"]) and !isset($_SESSION["username"])) {
quit();
}

if (isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$user = new Credential();
$user->readFile(); // read the file first to get the username and password
if (!isset($_SESSION["username"]) and $username == $user->getUsername()
and $password == $user->getPassword()) {
$_SESSION["username"] = $username;
} else {
quit();
}
}
?>
Example: nav.php (cont.)

<nav>
<a href="home.php">Home</a>
<a href="contact.php">Contact</a>
<?php
if (isset($_SESSION["username"])) {
?>
<span>
<?php echo("Hello, {$_SESSION["username"]}"); ?>
</span>
<a href="logout.php">Log Out</a>
<?php
}
?>
</nav>
Details
Notice here: we use the constructor and destructor to open and close a file
function __construct() {
$this->file = fopen("user.txt", "r") or die("Unable to open file");
}

function __destruct() {
fclose($this->file);
}
Details
Notice here: we use function to read one line and explode by “;” to get data

function readFile() {
$info = fgets($this->file);
$infoArray = explode(";", $info);
$this->username = $infoArray[0];
$this->password = $infoArray[1];
}
Exercise

Simulate an e-commerce application using session. The user could

1. Log In into the application


2. The user could add items into cart that could be saved in session
References
https://www.w3schools.com/php/php_cookies.asp

https://www.geeksforgeeks.org/php-cookies/

https://www.w3schools.com/php/php_sessions.asp

R. Nixon. Learning PHP, MySQL & JavaScript (California: O’Reilly, 2021),


p. 300-305.

You might also like