1

我已经坚持了几天了,我真的很难让这个脚本正常运行。

我有一个非常基本的启动脚本,每次页面刷新时都会输出一个随机的 text/html/php 页面。

<?php
$pages = array(1 => 'text1-1.php', 2 => 'text1-2.php', 3 => 'text1-3.php', 4 => 'text1-  4.php');
$key = array_rand ( $pages );
include($pages[$key]) ;
?>

我的目标是有一个脚本,它仅每 1 或 2 天(或指定的时间)更改输出,因此无论您刷新页面多少次,在计时器到期之前输出都不会改变。

我已经尝试从人们给我的提示中拼凑出以下内容,但无论我尝试什么脚本总是输出不同的东西,每次刷新页面时。

我认为问题是文件没有缓存,但我不明白为什么。

如果您还可以看到任何其他问题,我将不胜感激。:)

感谢您提供的任何帮助。:)

<?php
$pages = array(1 => 'text1-1.php', 2 => 'text1-2.php', 3 => 'text1-3.php', 4 => 'text1-   4.php');

$cachefile = "cache/timer.xml";
$time = $key = null;
$time_expire = 24*60*60;

if(is_file($cachefile)) {
    list($time, $key) = explode(' ', file_get_contents($cachefile));
}

if(!$time || time() - $time > $time_expire) {
    $key = rand(0,count($pages)-1);
    file_put_contents($cachefile, time().' '.$key);
}
include($pages[$key]) ;
?>
4

3 回答 3

2

这个方法如何生成你的随机数:

srand(floor(time()/60/60/24/2));
$key = rand(0,count($pages)-1);

它将种子固定两天(技术上是 48 小时,不一定匹配整整两天),所以第一次调用 rand() 总是返回基于该种子的第一个数字。

于 2012-04-05T15:04:18.023 回答
1

您是否检查过以确保该文件是实际创建的?目录“缓存”是否存在?您可以将 Web 服务器进程写入它吗?请注意,file_put_contents 只有在无法创建文件时才会发出警告;如果您将服务器设置为不显示警告,则不会产生任何错误,并且脚本似乎可以正常运行。

我绝对同意该文件没有被写入;你的代码对我来说很好。没有缓存/:

Warning: file_put_contents(cache/timer.xml): failed to open stream: No such file or directory in ...

具有缓存/和写权限:

$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
$ php test.php
text1-1.php
于 2012-04-05T15:06:34.887 回答
1

代替

if(!$time || time() - $time > $time_expire) {

if (! $time || (time () - $time) > $time_expire) {

mt_randrand你想改变的要好

编辑 1

既然你array不是开始形式0,你也应该

代替

$key = rand(0,count($pages)-1);

$key = mt_rand( 1, count ( $pages ));

或者

做你的阵列

$pages = array (
        0 => 'text1-1.php',
        1 => 'text1-2.php',
        2 => 'text1-3.php',
        3 => 'text1-4.php' 
);

现在测试了你的脚本......它工作得很好......让我知道你是否需要其他任何东西

谢谢

:)

于 2012-04-05T15:11:13.783 回答