UECS2094 UECS 2194 - Topic 5 Part 4
UECS2094 UECS 2194 - Topic 5 Part 4
Scripting
using PHP (part 4)
COOKIES AND SESSIONS
1
Recap
PHP syntax
• Data types
• Variables
PHP form handling
• Form validation
MySQL Database with PHP
PHP file handling
Cookies and Sessions
2
Cookies
A cookie is a small text file that is stored on the client's computer by the server.
Cookies are used to store information about the client's session or preferences, such as
login credentials or language preference.
Cookies are sent with every HTTP request to the server, allowing the server to access the
information stored in them.
Cookies can be created in PHP using the setcookie() function, which takes several
parameters including the cookie name, value, expiration time, and path.
Cookies can be accessed in PHP using the $_COOKIE superglobal array.
3
Cookies
5
Sessions
7
Cookies vs sessions
Cookies and sessions can be used together to provide a more robust user experience.
For example, a session can be used to store a user's shopping cart, while a cookie can be
used to store their login information so they don't have to log in every time they visit the
site.
8
Setting a cookie
Setting a cookie in PHP involves using the setcookie() function, which allows you to set the
cookie name, value, expiration time, path, domain, and security options.
setcookie(name, value, expire, path, domain, secure, httponly);
9
Setting a cookie
Example 1:
// set a cookie with the name "username" and the value "john"
setcookie("username", "john");
Example 2:
// This sets a cookie named "username" with the value "John", which
expires in one hour. The cookie is available in the entire domain, is
secure, and is only accessible through the HTTP protocol.
setcookie("username", "John", time()+3600, "/", ".example.com", true,
true);
10
Retrieving a cookie
To retrieve a cookie in PHP, you can use the $_COOKIE superglobal variable. This variable is an
associative array that contains all the cookies that were sent in the HTTP request.
To retrieve a specific cookie, you can access it using its name as the key in the $_COOKIE array.
For example, if you have a cookie named mycookie, you can retrieve its value like this:
if (isset($_COOKIE['mycookie'])) {
$value = $_COOKIE['mycookie'];
// Do something with the cookie value
}
Note that you should always check if a cookie exists before trying to access it, as not all requests
may contain the cookie.
Also, be aware that cookies can be modified by the user or intercepted by attackers, so you should
never store sensitive information in cookies.
11
Deleting a cookie
Deleting a cookie in PHP is a simple process that involves setting the cookie's expiration time to a
time in the past. This tells the browser that the cookie is expired and should be deleted.
In the above example, the setcookie function is called with an expiration time of one hour ago.
This will cause the browser to delete the cookie. The unset function is then used to remove the
cookie from the $_COOKIE array in case it is accessed later in the script.
It's important to note that when deleting a cookie, you must use the same parameters (name,
path, domain, etc.) that were used when the cookie was originally set. Otherwise, the browser
may not recognize the cookie as the same one and fail to delete it.
12
Starting a session
To start a session in PHP, you need to use the session_start() function at the beginning of
your script before any output is sent to the browser. This function will either start a new session or
resume an existing session that was started on a previous page.
Once the session is started, you can set session variables using the $_SESSION superglobal array
<?php
session_start();
$_SESSION['username'] = 'JohnDoe';
?>
In this example, we are setting a session variable called username and giving it the value of
JohnDoe.
13
Retrieving a session data
To retrieve session data, you can access the session variables using the $_SESSION superglobal
array. Here's an example:
<?php
session_start();
echo 'Welcome, ' . $_SESSION['username'];
?>
In this example, we are retrieving the username session variable and using it to display a
personalized welcome message to the user.
It's important to note that session variables are only available within the same session. Once the
session ends, the variables will be lost.
14
Destroying a session
To destroy a session and all of its variables, you can use the session_destroy() function.
Here's an example:
<?php
session_start();
session_destroy();
?>
This will destroy the current session and all of its variables. It's also a good practice to unset any
session variables that you no longer need using the unset() function. Here's an example:
<?php
session_start();
//unsetting the username session variable.
unset($_SESSION['username']);
?>
15
Example
// Start the session • First start the session using
session_start();
session_start(). Then set two
// Set session variables session variables, username and email,
$_SESSION['username'] = 'JohnDoe'; using the $_SESSION superglobal.
$_SESSION['email'] = 'johndoe@example.com'; • To retrieve the values of these variables,
// Retrieve session variables
simply assign them to local variables
$username = $_SESSION['username']; $username and $email.
$email = $_SESSION['email'];
• Next, unset the email session variable
echo "Username: $username<br>Email: $email<br>";
using the unset() function.
// Unset a session variable • Finally, destroy the entire session using
unset($_SESSION['email']); session_destroy(). Once the
session is destroyed, all session variables
// Destroy the session
session_destroy(); are cleared and the user is logged out.
16
Important considerations when
using cookies and sessions
Cookies can be deleted or modified by the client, so they should not be used to store
sensitive information such as passwords.
Sessions can be used to store sensitive information, but they are vulnerable to session
hijacking attacks if the session ID is stolen by an attacker.
To prevent session hijacking, session IDs should be regenerated periodically and stored
securely, and session data should be encrypted if possible.
It is also important to consider the lifetime of cookies and sessions, and to delete them
when they are no longer needed to prevent unnecessary data from being stored on the
client or server.
17
Common applications of cookies
and sessions
Storing user preferences and settings
Remembering login information
Tracking user behavior and analytics
Storing shopping cart and checkout information
Maintaining user sessions on a website.
18
Example: User login
<?php // Set a cookie to remember the user's login
// Start a session information
session_start(); setcookie('email', $email, time() + (86400 * 30),
'/');
// Check if the user is already logged in setcookie('password', $password, time() + (86400
if(isset($_SESSION['user_id'])) { * 30), '/');
// Redirect the user to the homepage
header("Location: index.php"); // Store the user ID in the session
exit; $_SESSION['user_id'] = 1;
}
// Redirect the user to the homepage
// Check if the form has been submitted header("Location: index.php");
if($_SERVER['REQUEST_METHOD'] == 'POST') { exit;
// Retrieve the form data } else {
$email = $_POST['email']; // Display an error message
$password = $_POST['password']; $error = 'Invalid email or password.';
}
// Validate the form data (omitted for brevity) }
?>
// Check if the email and password are correct
if($email == 'user@example.com' && $password ==
'password’) {
19
Example: User status checking
<?php
// Start a session
session_start();
20
Example: User logout
<?php
// Start a session
session_start();
21
Industry applications using PHP
Facebook: PHP is used as the primary language for developing the world's largest social media platform,
Facebook. It has been used to build a robust and scalable system that can handle billions of users.
WordPress: WordPress is a popular content management system (CMS) that powers millions of websites
worldwide. It is built using PHP and provides a flexible and customizable platform for bloggers, businesses, and
other users.
Shopee: Shopee Malaysia uses PHP as one of its primary programming languages for web development. PHP is
well-suited for building scalable and efficient web applications, making it a popular choice for e-commerce
platforms like Shopee. It is also used to build the back-end systems for managing orders, payments, and other
important aspects of the business..
Moodle: Moodle is an open-source learning management system (LMS) that is built using PHP. It is used by
educational institutions and businesses to deliver online courses and training programs. It provides a range of
features, including course management, student tracking, and assessment tools.
22
PHP in Facebook
1. User Authentication: Facebook uses PHP to handle user authentication. When a user logs in
to their account, PHP scripts authenticate the user's credentials and create a session to keep
the user logged in.
2. News Feed: Facebook's news feed feature is built using PHP. The system fetches data from
the database using PHP and displays it on the user's feed in real-time.
3. Messaging System: Facebook's messaging system is built using PHP. The system uses PHP to
handle the sending and receiving of messages between users.
4. User Data Management: Facebook stores user data in a MySQL database, and PHP scripts
are used to manage the data. The system uses PHP to handle queries, inserts, updates, and
deletes in the database.
5. Advertisement System: Facebook's advertising platform is built using PHP. The system uses
PHP to display relevant ads to users based on their interests and behaviors.
23
PHP in Shopee Malaysia
1. User authentication and authorization: When users log in to their accounts on Shopee, PHP
scripts are used to validate their credentials, store session data, and authorize access to various
features.
2. Product search and display: PHP is used to query the Shopee database and retrieve product
data based on search criteria entered by users. This data is then displayed in a visually
appealing and user-friendly manner.
3. Shopping cart and checkout: PHP scripts are used to manage users' shopping carts and handle
the checkout process, including calculating totals, applying discounts, and processing payments.
4. Order tracking and management: PHP is used to manage users' orders, including tracking
shipment status, updating inventory levels, and generating reports.
5. Customer support: PHP scripts are used to handle customer support requests, including
responding to inquiries, resolving disputes, and issuing refunds.
24
Summary
Cookies and sessions are important tools in web development that allow developers to
store and retrieve user data.
Cookies are small pieces of data that are stored on the user's computer, while sessions are
stored on the server.
Both cookies and sessions can be used to remember user information, such as login
credentials and shopping cart contents.
25
Summary
PHP is a popular server-side scripting language used in a variety of industries, including e-
commerce, social media, and content management.
It is commonly used for building dynamic websites and web applications, with a focus on
server-side scripting, database integration, and object-oriented programming.
Popular PHP-based applications include WordPress, Facebook, and Shopee.
26
Conclusion
In this topic, we have covered the basics of PHP, including its syntax, data types, functions,
arrays, form handling, MySQL database interaction, file handling, cookies, and sessions.
PHP is a popular server-side scripting language that is widely used in web development,
especially for building dynamic web applications. It offers many useful features and libraries
that allow developers to create complex web applications efficiently.
By learning PHP, you have gained a valuable skill that is in high demand in the industry.
Whether you want to build websites for clients, work for a tech company, or start your own
web-based business, PHP is a tool that can help you achieve your goals.
27
Sample question
TOPIC 5
28
Q. Write the complete statements in PHP to execute each of the following SQL
operations. All the statements are related to each other.
a) Create a new database called employeeDB.
b) Create a table named jobs including columns job_id, job_title, min_salary, max_salary.
29
Q. Write the complete statements in PHP to execute each of the following SQL
operations. All the statements are related to each other.
a) Create a new database called employeeDB.
CREATE DATABASE employeeDB
b) Create a table named jobs including columns job_id, job_title, min_salary, max_salary.
CREATE TABLE jobs (
job_id INT(11) PRIMARY KEY,
job_title VARCHAR(50),
min_salary INT(11),
max_salary INT(11)
)
30
Q. Write the complete statements in PHP to execute each of the following SQL
operations. All the statements are related to each other.
c) Write the code to check whether the max_salary amount exceed the upper limit 25000
31
Q. Write the complete statements in PHP to execute each of the following SQL
operations. All the statements are related to each other.
c) Write the code to check whether the max_salary amount exceed the upper limit 25000
$sql = "SELECT * FROM jobs WHERE max_salary > 25000";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "The maximum salary limit has been exceeded";
} else {
echo "The maximum salary limit is within the allowed range";
}
32
Q. Write the complete statements in PHP to execute each of the following SQL
operations. All the statements are related to each other.
d) Write the statement for inserting the following data in the employee table.
JOB_ID: 008
JOB_TITLE: Web Developer
MIN SALARY: RM3000
MAX SALARY: RM10000
33
Q. Write the complete statements in PHP to execute each of the following SQL
operations. All the statements are related to each other.
d) Write the statement for inserting the following data in the employee table.
JOB_ID: 008
JOB_TITLE: Web Developer
MIN SALARY: RM3000
MAX SALARY: RM10000
34
Q. Write a simple calculator utility-program, which can be used to calculate a
person's Body Mass Index (BMI). Implement simple HTML-form (bmi.html) where
user can input weight (in kilograms) and height (in meters).
Calculate
Example form
35
How to answer?
Ö Two-part answer:
◦ HTML Form
Height input field
Weight input field
Calculate button
◦ PHP code for BMI calculation
BMI formula:
• Weight (kg) / Height2 (m2)
36
1. HTML form
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<h1>BMI Calculator</h1>
<form action="bmi.php" method="post">
<label for="weight">Weight (kg):</label>
<input type="text" name="weight" id="weight" required><br>
<label for="height">Height (m):</label>
<input type="text" name="height" id="height" required><br>
<input type="submit" value="Calculate">
</form>
</body>
</html>
37
2. PHP
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator Result</title>
</head>
<body>
<h1>BMI Calculator Result</h1>
<?php
if(isset($_POST['weight']) && isset($_POST['height'])) {
$weight = $_POST['weight'];
$height = $_POST['height'];
$bmi = $weight / ($height * $height);
echo "<p>Your BMI is: " . number_format($bmi, 2) . "</p>";
} else {
echo "<p>Invalid input.</p>";
}
?>
<a href="bmi.html">Calculate Again</a>
</body>
</html>
38
Quiz
CHECK YOUR UNDERSTANDING ON PHP
~ H IGH E S T M A R K S W I T H T H E FA S T E S T S P E E D GE T S BON U S
M AR K S ~
39
Google Quiz
https://forms.gle/6m8Ff9fFS6ERDfqw6
40