簡體   English   中英

PHP 計時器腳本,無法將文件緩存

[英]PHP Script on timer, can't get file to cache

我已經堅持了幾天了,我真的很難將這個腳本正確地發送到 function。

我有一個非常基本的啟動腳本,每次刷新頁面時都會輸出一個隨機的 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 天(或指定的任何時間)更改 output,因此無論您刷新頁面多少次,output 都不會更改,直到計時器到期。

我已經根據人們給我的提示拼湊了以下內容,但無論我嘗試什么,每次刷新頁面時,腳本總是輸出不同的東西。

我認為問題是文件沒有緩存,但我不明白為什么。

如果大家看到還有什么問題,不勝指點。 :)

感謝您提供的任何幫助。 :)

<?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]) ;
?>

這個方法如何生成你的隨機數:

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

它將種子修復兩天(技術上是 48 小時,不一定匹配整整兩天),因此第一次調用 rand() 總是返回基於該種子的第一個數字。

您是否檢查過以確保該文件確實已創建? 目錄“緩存”是否存在? 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

代替

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' 
);

現在測試你的腳本..它工作得很好......如果你還需要什么,請告訴我

謝謝

:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM