07.PHP Cookies and Sessions
07.PHP Cookies and Sessions
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
<?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
$_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();
}
?>
<?php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
?>
require_once("function.php");
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
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");
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
https://www.geeksforgeeks.org/php-cookies/
https://www.w3schools.com/php/php_sessions.asp