SlideShare a Scribd company logo
1 of 18
To start a session in PHP, you need to call the
session_start() function at the beginning of your script. This
function initializes the session and makes session-related
data accessible via the $_SESSION superglobal.
2
<?php
session_start();
?>
3
To store data in the $_SESSION array to make it
accessible across multiple requests. This data persists
until the session is destroyed or the user logs out.
$_SESSION['username'] = 'john_doe';
$_SESSION['cart'] = ['item1', 'item2', 'item3'];
4
To retrieve data from a session, you can simply access
the $_SESSION array.
$username = $_SESSION['username'];
$cartItems = $_SESSION['cart'];
5
To modify session data just like any other PHP array.
$_SESSION['cart'][] = 'item4'; // Add an item to the cart
$_SESSION['username'] = 'jane_doe'; // Update the
username
6
To remove a specific item from the session, you can use
the unset() function.
unset($_SESSION['cart'][1]); // Remove the second item
from the cart
7
To end a session, call the session_destroy() function. This
clears all session data and cookies associated with the
session. However, this doesn't unset the $_SESSION
superglobal, so any session data set during the script
execution will still be accessible until the script finishes
running.
session_destroy();
8
Sessions have a timeout period defined in PHP
configuration. By default, this is set to 24 minutes. If a
user remains inactive for this duration, their session data
will be automatically destroyed.
9
Sessions should be used carefully to avoid security risks
like session fixation, session hijacking, and session data
manipulation. To enhance security, use techniques like
session ID regeneration (session_regenerate_id()) and
use secure cookies.
10
// During login
if ($validCredentials) {
$_SESSION['user_id'] = $userId;
}
// On protected pages
session_start();
if (!isset($_SESSION['user_id'])) {
// Redirect to login page
}
11
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['user_input'] = $_POST['input_data'];
header('Location: display.php');
exit();
}
?>
<form method="post" action="">
<input type="text" name="input_data" placeholder="Enter data">
<button type="submit">Submit</button>
</form>
12
<?php
session_start();
if (isset($_SESSION['user_input'])) {
echo "User input: " . $_SESSION['user_input'];
} else {
echo "No user input found.";
}
?>
13
<?php
session_start();
$products = [
['id' => 1, 'name' => 'Product A', 'price' => 10.99],
['id' => 2, 'name' => 'Product B', 'price' => 15.99],
['id' => 3, 'name' => 'Product C', 'price' => 7.49],
];
if (isset($_POST['add_to_cart'])) {
$productId = $_POST['product_id'];
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = $productId;
}
?>
14
<!DOCTYPE html>
<html>
<head>
<title>Simple Shopping Cart Example</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php foreach ($products as $product): ?>
<li>
<?php echo $product['name']; ?> - $<?php echo $product['price']; ?>
<form method="post">
<input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
<input type="submit" name="add_to_cart" value="Add to Cart">
</form>
</li>
<?php endforeach; ?>
</ul>
<h2><a href="cart.php">View Cart</a></h2>
</body>
</html>
15
<?php
session_start();
$products = [
['id' => 1, 'name' => 'Product A', 'price' => 10.99],
['id' => 2, 'name' => 'Product B', 'price' => 15.99],
['id' => 3, 'name' => 'Product C', 'price' => 7.49],
];
function getProductById($id) {
global $products;
foreach ($products as $product) {
if ($product['id'] == $id) {
return $product;
}
}
return null;
}
$cartItems = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$totalPrice = 0;
?>
16
<html>
<head>
<title>Shopping Cart</title>
</head>
<body>
<h1>Shopping Cart</h1>
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<?php foreach ($cartItems as $itemId): ?>
<?php $product = getProductById($itemId); ?>
<?php if ($product): ?>
<tr>
<td><?php echo $product['name']; ?></td>
<td>$<?php echo $product['price']; ?></td>
</tr>
<?php $totalPrice += $product['price']; ?>
<?php endif; ?>
<?php endforeach; ?>
<tr>
<th>Total</th>
<th>$<?php echo $totalPrice; ?></th>
</tr>
</table>
</body>
</html>
17
18

More Related Content

Similar to Unit 3 - for php application Sessions.pptx

Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Francois Marier
 
The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageLovely Professional University
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Francois Marier
 
Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018Elliot Taylor
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operationsyeda zoya mehdi
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
how would i fix my code- any login doesnt work but it should retrieve.docx
how would i fix my code- any login doesnt work but it should retrieve.docxhow would i fix my code- any login doesnt work but it should retrieve.docx
how would i fix my code- any login doesnt work but it should retrieve.docxJacobUasThomsoni
 

Similar to Unit 3 - for php application Sessions.pptx (20)

Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
 
The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
 
PHP || [Student Result Management System]
PHP || [Student Result Management System]PHP || [Student Result Management System]
PHP || [Student Result Management System]
 
Amp Up Your Admin
Amp Up Your AdminAmp Up Your Admin
Amp Up Your Admin
 
Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018Building scalable products with WordPress - WordCamp London 2018
Building scalable products with WordPress - WordCamp London 2018
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operation
 
Php
PhpPhp
Php
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Add loop shortcode
Add loop shortcodeAdd loop shortcode
Add loop shortcode
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Php session
Php sessionPhp session
Php session
 
23. CodeIgniter sessions
23. CodeIgniter sessions23. CodeIgniter sessions
23. CodeIgniter sessions
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
Facebook
FacebookFacebook
Facebook
 
how would i fix my code- any login doesnt work but it should retrieve.docx
how would i fix my code- any login doesnt work but it should retrieve.docxhow would i fix my code- any login doesnt work but it should retrieve.docx
how would i fix my code- any login doesnt work but it should retrieve.docx
 

Recently uploaded

KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Unit 3 - for php application Sessions.pptx

  • 1.
  • 2. To start a session in PHP, you need to call the session_start() function at the beginning of your script. This function initializes the session and makes session-related data accessible via the $_SESSION superglobal. 2
  • 4. To store data in the $_SESSION array to make it accessible across multiple requests. This data persists until the session is destroyed or the user logs out. $_SESSION['username'] = 'john_doe'; $_SESSION['cart'] = ['item1', 'item2', 'item3']; 4
  • 5. To retrieve data from a session, you can simply access the $_SESSION array. $username = $_SESSION['username']; $cartItems = $_SESSION['cart']; 5
  • 6. To modify session data just like any other PHP array. $_SESSION['cart'][] = 'item4'; // Add an item to the cart $_SESSION['username'] = 'jane_doe'; // Update the username 6
  • 7. To remove a specific item from the session, you can use the unset() function. unset($_SESSION['cart'][1]); // Remove the second item from the cart 7
  • 8. To end a session, call the session_destroy() function. This clears all session data and cookies associated with the session. However, this doesn't unset the $_SESSION superglobal, so any session data set during the script execution will still be accessible until the script finishes running. session_destroy(); 8
  • 9. Sessions have a timeout period defined in PHP configuration. By default, this is set to 24 minutes. If a user remains inactive for this duration, their session data will be automatically destroyed. 9
  • 10. Sessions should be used carefully to avoid security risks like session fixation, session hijacking, and session data manipulation. To enhance security, use techniques like session ID regeneration (session_regenerate_id()) and use secure cookies. 10
  • 11. // During login if ($validCredentials) { $_SESSION['user_id'] = $userId; } // On protected pages session_start(); if (!isset($_SESSION['user_id'])) { // Redirect to login page } 11
  • 12. <?php session_start(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $_SESSION['user_input'] = $_POST['input_data']; header('Location: display.php'); exit(); } ?> <form method="post" action=""> <input type="text" name="input_data" placeholder="Enter data"> <button type="submit">Submit</button> </form> 12
  • 13. <?php session_start(); if (isset($_SESSION['user_input'])) { echo "User input: " . $_SESSION['user_input']; } else { echo "No user input found."; } ?> 13
  • 14. <?php session_start(); $products = [ ['id' => 1, 'name' => 'Product A', 'price' => 10.99], ['id' => 2, 'name' => 'Product B', 'price' => 15.99], ['id' => 3, 'name' => 'Product C', 'price' => 7.49], ]; if (isset($_POST['add_to_cart'])) { $productId = $_POST['product_id']; if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = []; } $_SESSION['cart'][] = $productId; } ?> 14
  • 15. <!DOCTYPE html> <html> <head> <title>Simple Shopping Cart Example</title> </head> <body> <h1>Products</h1> <ul> <?php foreach ($products as $product): ?> <li> <?php echo $product['name']; ?> - $<?php echo $product['price']; ?> <form method="post"> <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>"> <input type="submit" name="add_to_cart" value="Add to Cart"> </form> </li> <?php endforeach; ?> </ul> <h2><a href="cart.php">View Cart</a></h2> </body> </html> 15
  • 16. <?php session_start(); $products = [ ['id' => 1, 'name' => 'Product A', 'price' => 10.99], ['id' => 2, 'name' => 'Product B', 'price' => 15.99], ['id' => 3, 'name' => 'Product C', 'price' => 7.49], ]; function getProductById($id) { global $products; foreach ($products as $product) { if ($product['id'] == $id) { return $product; } } return null; } $cartItems = isset($_SESSION['cart']) ? $_SESSION['cart'] : []; $totalPrice = 0; ?> 16
  • 17. <html> <head> <title>Shopping Cart</title> </head> <body> <h1>Shopping Cart</h1> <table> <tr> <th>Product</th> <th>Price</th> </tr> <?php foreach ($cartItems as $itemId): ?> <?php $product = getProductById($itemId); ?> <?php if ($product): ?> <tr> <td><?php echo $product['name']; ?></td> <td>$<?php echo $product['price']; ?></td> </tr> <?php $totalPrice += $product['price']; ?> <?php endif; ?> <?php endforeach; ?> <tr> <th>Total</th> <th>$<?php echo $totalPrice; ?></th> </tr> </table> </body> </html> 17
  • 18. 18