Session
Chansing Sem 640710176
เซสชั่น ในภาษาphp เป็นวิธีการเก็บข้อมูลในตัวแปรของผู้ใช้คนเดียวเท่านั้น เพื่อให้ใช้ได้ผ่านหลายๆเพจ
ที่จะเก็บจากผู้ใช้เวลาที่เข้าใช้ในทุกๆเพจของแอปพลิเคชัน จนทำการปิดเบราว์เซอร์
Real use case example
หน้าlogin(set)จะกรอก username กับ id ส่วนหน้า profile(retrieve) ก็จะทำการดึงข้อมูลเพิ่งกรอกมาใช้ต่อ
เว็บไซต์ช้อปปิ้งที่เราต้องจัดเก็บและส่งข้อมูลรถเข็น เช่น ชื่อผู้ใช้(username) รหัสผลิตภัณฑ์(idProduct) ชื่อผลิตภัณฑ์(nameProduct) ราคาสินค้า(price) ไปยังอีกหน้าหนึ่ง
ฟังชั่นที่ถูกใช้บ่อย
การเริ่มต้น (start)
session_start()
การ set
$_SESSION["variable"] = value;
การพิมพ์ (display)
echo $_SESSION["variable"];
การเปลี่ยนแปลง (modify)
$_SESSION["variable"] = new_value;
การลบ ( remove)
session_unset();
การทำลาย ( destroy)
session_destroy();
variable คือชื่อ (key) ของ session variable ที่ต้องการจัดเก็บข้อมูลหรือเปลี่ยนแปลงข้อมูล
value คือค่าที่ถูกจัดเก็บใน session variable ตอนที่กำหนดค่าให้กับตัวแปร
new_value คือค่าที่ถูกกำหนดใหม่ (หรือค่าที่เปลี่ยนแปลง) สำหรับ session variable ที่มีอยู่
Pros and Cons
ช่วยรักษาข้อมูลผู้ใช้ในหน้าต่างๆ
การจัดการใน distributed systems อาจเป็นเรื่องท้าทาย (Scalability)
ข้อมูลถูกเก็บไว้บนเซิร์ฟเวอร์ ซึ่งให้ความปลอดภัยที่ดีกว่าคุกกี้ฝั่งไคลเอ็นต์
ต้องใช้ทรัพยากรเซิร์ฟเวอร์ (server resources) ซึ่งอาจทำให้trafficเพิ่มขึ้นได้
สามารถหมดอายุได้หลังจากไม่มีการใช้งาน ซึ่งช่วยเพิ่มความปลอดภัย
ข้อกังวลเรื่องSecurity
ฟังก์ชันใช้งานได้ตรงไปตรงมาของ PHP เช่น session_start()
ในการ fix ต้องมีการดำเนินการอย่างระมัดระวัง
Session Vs Cookies
ความปลอดภัยสูง
ความปลอดภัยต่ำ
จัดเก็บข้อมูลบนเซิร์ฟเวอร์
จัดเก็บไว้ในคอมพิวเตอร์ของผู้ใช้
เชื่อมโยงผู้ใช้กับข้อมูลบนเซิร์ฟเวอร์
ส่งข้อมูลผู้ใช้ทุกครั้งเวลาที่ผู้ใช้เข้าดูหน้าเว็บ
ตัวอย่างโค้ด (set และ get ): PHP, C ,Java, Python, JavaScript
Output
Session variables are set.
Favorite color is green.
Favorite animal is cat.
Session variables are set.
Favorite color is green.
Favorite animal is cat.
Favorite color is green.
Favorite animal is cat.
Favorite color is green.
Favorite animal is cat.
Session variables are set.
Favorite color is green.
Favorite animal is cat.
PHP ต้องแยกไฟล์กัน Set กับ Get เพราะหลักการของ session ในภาษา php เพื่อให้หลายเพจเข้าใช้งานด้วยกัน
C, Java, Python, JavaScript สามารถเขียนเข้าด้วยกันได้
สไลด์ :
วิดีโอ : https://youtu.be/FRXxp9uEeh4
การอ้างอิง
W3Schools. (n.d.). PHP sessions. W3Schools. https://www.w3schools.com/php/php_sessions.asp
GeeksforGeeks. (n.d.). What is a session and how to start a session in PHP? GeeksforGeeks. https://www.geeksforgeeks.org/what-is-a-session-and-how-to-start-a-session-in-php/
GeeksforGeeks. (n.d.). PHP sessions. GeeksforGeeks. https://www.geeksforgeeks.org/php-sessions/
PHP Manual. (n.d.). Session handling. PHP.net. https://www.php.net/manual/en/book.session.php
Javatpoint. (n.d.). PHP session. Javatpoint. https://www.javatpoint.com/php-session
Last updated