如何防止PHP随机模板被重复引入?
Solution: Use PHP Sessions to Track Used Templates
Hey there! The problem with your current code is that each page refresh is a fresh request—there's no way to remember which templates were already included. To fix this, we can use PHP sessions to persist the list of used templates across refreshes. Here's a step-by-step implementation:
<?php // Start or resume a session to store data between page loads session_start(); // Define your full list of templates $templates = array("template1.php", "template2.php", "template3.php"); // Initialize the used templates array in the session if it doesn't exist if (!isset($_SESSION['used_templates'])) { $_SESSION['used_templates'] = array(); } // Create a list of templates that haven't been used yet $available_templates = array_diff($templates, $_SESSION['used_templates']); // If all templates have been used, reset the list to start over if (empty($available_templates)) { $_SESSION['used_templates'] = array(); $available_templates = $templates; } // Pick a random template from the available options $random_template = $available_templates[array_rand($available_templates, 1)]; // Add the selected template to the used list in the session $_SESSION['used_templates'][] = $random_template; // Include the chosen template include $random_template; ?>
How this works:
session_start(): This kicks off a user-specific session, letting us store data (like used templates) that persists across page refreshes.- Tracking used templates: The
$_SESSION['used_templates']array keeps a record of every template that's been included. - Filtering available templates:
array_diff()compares the full template list with the used list to get only the templates that haven't been loaded yet. - Resetting when exhausted: If all templates are used, we clear the used list so the cycle starts fresh.
- Random selection: We pick a random entry from the available templates, add it to the used list, then include it.
This ensures you'll never get the same template twice in a row until all options have been exhausted, at which point it starts over.
内容的提问来源于stack exchange,提问作者user9402741
相关产品推荐
相关产品推荐

