您可以使用会话 cookie 来保存随机的、不重复的文件列表。实际上,为了安全起见,会话 cookie 应该只将 indices 列表存储到文件数组中。
例如,假设我们在一个数组中有以下文件列表:
index file
----------------------------
0 spelling/file1.txt
1 spelling/file2.txt
2 spelling/file3.txt
3 spelling/file4.txt
我们可以创建一个索引数组,例如 array(0,1,2,3),将它们打乱以获得类似array(3,2,0,1) 的内容,并将那个列表存储在cookie中。然后,随着我们遍历这个随机的索引列表,我们得到序列:
spelling/file4.txt
spelling/file3.txt
spelling/file1.txt
spelling/file2.txt
cookie 还将当前位置存储在这个索引列表中,当它到达末尾时,我们重新洗牌并重新开始。
我意识到这一切听起来可能有点令人困惑,所以也许这张华丽的图表会有所帮助:
…或者一些代码:
<?php
$fictional = glob("spelling/*.php"); // list of files
$max_index = count($fictional) - 1;
$indices = range( 0, $max_index ); // list of indices into list of files
session_start();
if (!isset($_SESSION['indices']) || !isset($_SESSION['current'])) {
shuffle($indices);
$_SESSION['indices'] = serialize($indices);
$_SESSION['current'] = 0; // keep track of which index we're on
} else {
$_SESSION['current']++; // increment through the list of indices
// on each reload of the page
}
// Get the list of indices from the session cookie
$indices = unserialize($_SESSION['indices']);
// When we reach the end of the list of indices,
// reshuffle and start over.
if ($_SESSION['current'] > $max_index) {
shuffle($indices);
$_SESSION['indices'] = serialize($indices);
$_SESSION['current'] = 0;
}
// Get the current position in the list of indices
$current = $_SESSION['current'];
// Get the index into the list of files
$index = $indices[$current];
// include the pseudo-random, non-repeating file
include( $fictional[$index] );
?>