20 กุมภาพันธ์ 2552

การกำหนดอายุของ session

ปกติแล้ว session จะมีระยะเวลาการคงอยู่ช่วงเวลาหนึ่งตามที่กำหนดใน session_cache_expire ที่ php.ini ซึ่งมีค่าปกติเป็น 180 นาที ในบางครั้ง เราอาจต้องการกำหนด อายุของ session ด้วยตัวเอง เช่น การกำหนด ช่วงเวลาการ login ให้สามารถอยู่บนระบบได้แค่ช่วงเวลาหนึ่ง (สั้นๆ) หรือบางครั้งเราอาจต้องการเปิดเพจทิ้งไว้เป็นเวลานานๆ เพื่อไม่ให้ session หมดอายุไปก่อนที่เราจะปิดถึงแม้เราจะม่ทำอะไรก็ตาม เช่น การเฝ้าดูตลาดหุ้น หรือ โปรแกรม chat เป็นต้น

การกำหนดอายุของ session สามารถทำได้หลายวิธีคือ
1. แก้ไขค่านี้ใน php.ini ประมาณนี้

[Session]

; Document expires after n minutes.
session.cache_expire = 180


2. กำหนดค่าใน htaccess

php_value session.cache_expire 3000000


ถ้ายังไม่มีไฟล์ htaccess ให้สร้างไฟล์นี้เปล่าๆ บน server ที่ root ของ website แล้ว ใส่ข้อความด้านบนลงในไฟล์ การกำหนดแบบนี้ จะมีผลเหมือนกับการกำหนด ใน php.ini คือมีผลกับทั้ง Server

3. กำหนดเมือต้องการ ใน php

<?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* set the cache expire to 30 minutes */
session_cache_expire(
30);
$cache_expire = session_cache_expire();

/* start the session */

session_start();

echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>

 

ไม่มีความคิดเห็น: