php - 无法打开带会话的include_once

时间:2014-01-23 21:07:34

标签: php session random include

我想在浏览我的.php文件时随机包含一个html文件。 我不希望刷新后可以在彼此之后显示两次相同的页面。

我以为我可以使用会话实现这一点,但我似乎在规则28的某些时候出现了一些错误(include_once($ htmls [$ rand]);):

Notice: Undefined index: in C:\Users\Roderik\Documents\Casimir\root\final.php on line 28

Warning: include_once(C:\Users\Roderik\Documents\Casimir\root): failed to open stream: Permission denied in C:\Users\Roderik\Documents\Casimir\root\final.php on line 28

Warning: include_once(): Failed opening '' for inclusion (include_path='.;C:\php\pear') in C:\Users\Roderik\Documents\Casimir\root\final.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;
    }
}

2 个答案:

答案 0 :(得分:1)

作为错误

Notice: Undefined index: in C:\Users\Roderik\Documents\Casimir\root\final.php on line 28

说,你在$rand中用作索引的$htmls[$rand]是未定义的,并返回一个null,在include()中被视为空字符串,所以你有效运行

include('')

var_dump($htmls)来电之前立即执行echo $randinclude(),并查看您要使用的内容。

答案 1 :(得分:0)

你过度复杂化了。以下内容将确保文件不会连续两次包含。

// 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];