File manager - Edit - /var/www/order.cmtc.ac.th/includes/auto_clear_reserved.php
Back
<?php echo "<meta charset=\"UTF-8\">"; /** * 🔄 auto_clear_reserved.php * ------------------------------------------------------- * สคริปต์นี้ใช้สำหรับเคลียร์สินค้า (products.reserved) * ที่ถูกจองไว้โดยผู้ใช้ที่หมดเวลา session checkout ไปแล้ว * * ✅ ไม่ต้องเพิ่มตารางใหม่ * ✅ ใช้ร่วมกับระบบ session ปัจจุบันได้ทันที * ✅ แนะนำให้ตั้ง Cron Job รันทุก 10-15 นาที */ // */10 * * * * /usr/bin/php /var/www/order.cmtc.ac.th/includes/auto_clear_reserved.php > /dev/null 2>&1 /* * ------------------------------------------------------- */ //include('../config/db.php'); //$conn = new mysqli("localhost", "root", "", "cmtc_booking"); $conn = new mysqli("localhost", "order_cmtc", "order2922!", "order_cmtc"); if ($conn->connect_error) { die("Database connection failed: " . $conn->connect_error); } // 🕐 กำหนดเวลาหมดอายุของ session (หน่วย: นาที) $SESSION_LIFETIME = 30; // 📂 ที่เก็บไฟล์ session ของ PHP $session_path = ini_get('session.save_path'); if (!$session_path || !is_dir($session_path)) { $session_path = sys_get_temp_dir(); } // 🔍 คำนวณเวลาเกินกำหนด $expire_timestamp = time() - ($SESSION_LIFETIME * 60); $cleared_sessions = 0; $cleared_products = 0; // 🧹 วนตรวจสอบทุกไฟล์ session foreach (glob($session_path . '/sess_*') as $sess_file) { // ข้ามไฟล์ที่ยังไม่หมดอายุ if (filemtime($sess_file) > $expire_timestamp) continue; // อ่านข้อมูลใน session $data = @file_get_contents($sess_file); if (!$data) continue; // ตรวจว่ามีข้อมูลตะกร้า (cart) หรือไม่ if (strpos($data, 'cart|') !== false) { // ดึงข้อมูล cart (ตัวอย่างเช่น a:2:{i:5;i:1;i:7;i:2;}) if (preg_match('/cart\|.*?a:\d+:{(.*?)}/s', $data, $matches)) { $cart_data = $matches[1]; // ดึง id สินค้าและจำนวน (i:<pid>;i:<qty>) if (preg_match_all('/i:(\d+);i:(\d+)/', $cart_data, $found)) { foreach ($found[1] as $idx => $pid) { $qty = (int)$found[2][$idx]; $pid = (int)$pid; // คืนสินค้าในฐานข้อมูล $conn->query("UPDATE products SET reserved = GREATEST(reserved - $qty, 0) WHERE id = $pid"); $cleared_products++; } } } } // ลบไฟล์ session ที่หมดเวลาแล้ว @unlink($sess_file); $cleared_sessions++; } echo "✅ เคลียร์ session ที่หมดอายุแล้ว {$cleared_sessions} รายการ\n"; echo "✅ คืนสินค้า reserved แล้ว {$cleared_products} ชิ้น\n"; echo "🕒 เวลา: " . date('Y-m-d H:i:s') . "\n"; // ✅ บันทึก Log ลงไฟล์ $log_path = __DIR__ . '/auto_clear_log.txt'; $log_message = sprintf("[%s] เคลียร์ session %d รายการ | คืนสินค้า %d ชิ้น\n", date('Y-m-d H:i:s'), $cleared_sessions, $cleared_products); file_put_contents($log_path, $log_message, FILE_APPEND); ?>
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | Generation time: 0.44 |
proxy
|
phpinfo
|
Settings