开发者

Make PHP include randomizer not repeat itself

Situation

I have a relatively short php code I found and tweaked that includes a random html file from my 'randomizer' folder into my page.

Here is the code

<?php
  error_reporting(0);
  function random_file($string){
    return ((file_exists($string))&&(preg_match('#(\.html)$#i',$string)))  ? true : false ;
  }

  define('OUTPUT_TYPE','text');

  define('RANDOM_FILES_FOLDER','randomizer/');

  $my_array = Array();
  $my_dir = RANDOM_FILES_FOLDER ;

  if ($dir = @opendir("$my_dir")) {

    while (($file = readdir($dir)) !== false) {
      if ($file != "." && $file != ".."  && !is_dir($my_dir.$file))
      {
        switch(OUTPUT_TYPE):

          case'text':
            if(random_file($my_dir.$file)){
              $my_array[] = $file;
            }
          break;

          default:
          break;

        endswitch;

      }
    }
    closedir($dir);
  }

  if(count($my_array)>0){

    $random_number = rand(0, count($my_array)-1);
    $random_file = $my_array[$random_number];

    switch(OUTPUT_TYPE):

      case'text':
        include($my_dir.$random_file);
      break;

      default:
      break;

    endswitch;

  }
?>

Question

It does what it is supposed to do (perhaps someone can trim/optimize that code for me) but I have only a few files to randomize and I don't want the same file to appear twice when I refresh or open the page a day after.

I think cookies may be the answer, but not sure how to do anything开发者_运维技巧 with them.

Can anyone write a piece code to add to mine to do that or provide a code that has all those attributes? keep in mind it must include files at random from a folder, I don't want the code from those files on my actual page code for CMS purposes

Keep in mind I am a PHP and Javascript beginner with VERY basic knowledge, so please dumb it down for me.

Thanks!


Very rough:

session_start();
$dir = 'randomizer/';

if (empty($_SESSION['files'])) {
    $_SESSION['files'] = array_filter(scandir($dir), function ($file) use ($dir) {
        return is_file($dir . $file) && preg_match('#(\.html)$#i', $file);
    });
    shuffle($_SESSION['files']);
}

include $dir . array_shift($_SESSION['files']);

Keep a list of all candidate files in the session, use them one by one. That way all files will be displayed once in random order before the cycle starts again. Only not recommended if the list is very long.

It's worth noting that the array_filter callback syntax requires PHP 5.3.


This is not the perfect way to do this but it will work(intentionally simple): Include this after the line $random_file = $my_array[$random_number];

$oldFile = ''
if(!empty($_COOKIE['oldfilename']) {
    $oldFile = $_COOKIE['oldfilename'];
}
while ($oldFile == $random_file) {
    $random_number = rand(0, count($my_array)-1);
    $random_file = $my_array[$random_number];
}
setcookie('oldfilename', $random_file);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜