doudou5023 2012-03-18 23:55
浏览 93
已采纳

具有随机时间延迟的随机内容脚本

At the moment I have a really basic PHP script for randomly drawing quotes from a text file.

<?php include('testimonials.txt');
  srand ((double) microtime() * 100000);
  $random_number = rand(0,count($quotes)-1);
  echo ($quotes[$random_number]);
?>

Of course currently the script executes every time the page loads and brings up new content each time the page is refreshed.

I want to know is there any easy way to modify this to change the content on a timer, so it only changes once a day, or every few days?

If it requires altering the wp-cron.php of my site, any idea what I would need to put in there to do so?

Thank you

  • 写回答

2条回答 默认 最新

  • duanbo19834 2012-03-19 00:02
    关注

    You can start with something as basic as this, which saves the id of a quote and the time it was picked in a file:

    <?php
    $cachefile = './current_t_id';
    $time = $id = null; // assume we have no cached quote
    $change_every = 3600; // seconds
    include('testimonials.txt');
    
    // if cached quote exists, load it
    if(is_file($cachefile)) {
        list($time, $id) = explode(' ', file_get_contents($cachefile));
    }
    
    // if no cached quote or duration expired, change it
    if(!$time || time() - $time > $change_every) {
        srand ((double) microtime() * 100000);
        $id = rand(0,count($quotes)-1);
        file_put_contents($cachefile, time().' '.$id); // update cache
    }
    
    // echo the quote, be it cached or freshly picked 
    echo ($quotes[$id]);
    

    There are several things that can be improved here (e.g. error handling, the possibility of the testimonials file changing in a way that makes the cached quote invalid, etc) but the basic idea should be apparent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算