我想在浏览到我的.php文件时随机包含HTML文件。我不希望在刷新时彼此之间两次可以显示同一页。
我以为我可以使用会话来实现这一目标,但是在规则28上的某些时间似乎会遇到一些错误(包括_once($ htmls [$ rand]);):
Notice: Undefined index: in C:UsersRoderikDocumentsCasimirrootfinal.php on line 28
Warning: include_once(C:UsersRoderikDocumentsCasimirroot): failed to open stream: Permission denied in C:UsersRoderikDocumentsCasimirrootfinal.php on line 28
Warning: include_once(): Failed opening '' for inclusion (include_path='.;C:phppear') in C:UsersRoderikDocumentsCasimirrootfinal.php on line 28
我正在使用USB-Webserver进行测试。
我的代码:
session_start();
global $htmls;
global $arrlength;
//get all .html's withing ./pages
$htmls = glob('./pages/*.html');
$arrlength = count($htmls) - 1 ;
if (isset($_SESSION['rand'])) {
$session_rand = $_SESSION['rand'];
$rand = rand(0, $arrlength);
if($rand !== $session_rand)
{
$_SESSION['rand'] = $rand;
include_once($htmls[$rand]);
}
else
{
$rand = getNewRandom($session_rand, $arrlength);
$_SESSION['rand'] = $rand;
include_once($htmls[$rand]);
}
}
else
{
$rand = rand(0, $arrlength);
$_SESSION['rand'] = $rand;
include_once($htmls[$rand]);
}
function getNewRandom($exception, $arrlength)
{
$rand = rand(0, $arrlength);
if($rand == $exception)
{
getNewRandom($exception, $arrlength);
}
else
{
return $rand;
}
}
作为错误
Notice: Undefined index: in C:UsersRoderikDocumentsCasimirrootfinal.php on line 28
说,$rand
您正在使用$htmls[$rand]
中的索引未定义,并返回一个null,该null被视为include()
中的一个空字符串,因此您有效地运行
include('')
在您的include()
呼叫之前,请立即进行var_dump($htmls)
和echo $rand
,然后查看您要使用的内容。
您使事情复杂化。以下将确保连续两次不包括文件。
// Files
$htmls = glob('test/*.html');
// Get the key of the previously included file
$previous = false;
if ( isset($_SESSION['rand']) ) {
$previous = $_SESSION['rand'];
}
// If a file was previously included, remove it from the pool
if ( $previous !== false && isset($htmls[$previous]) ) {
unset($htmls[$previous]);
}
// Get a random key from available files
$key = $_SESSION['rand'] = array_rand($htmls);
// File to include
$include = $htmls[$key];