2

I have a folder which contains several html files: 1.html, 2.html, 3.html, etc., etc. in sequential order.

I would like for PHP to randomly load in these files into a PHP webpage that I have. How can I go about doing this?

Also -- is PHP the most efficient way to do this? Would jQuery be better?

tehSUPERADMIN
  • 269
  • 3
  • 5
  • 8
  • 5
  • 1
    This question/answer should be what you're looking for: http://stackoverflow.com/a/4478788/945775 Dave's answer can work, but the problem there is it doesn't account for knowing how many files are in the directory, so you'd have to add some extra code to make sure the maximum range matches how many files you actually have. – AgmLauncher Jul 21 '13 at 21:48
  • possible duplicate of [Select random file from directory](http://stackoverflow.com/questions/4478783/select-random-file-from-directory) – Steven V Jul 22 '13 at 18:42

1 Answers1

4

jquery could do it, but you'd have to send a list of the available files to the client beforehand, so it has a list to choose from. This would be required if you can't guaranteed there'll never be "holes" in the files, e.g. 1,2,4,5 (hey, where's 3?).

PHP can deal with the raw filesystem, and can always get the list of files, e.g.

<?php
$files = glob('*.html');
$random_file = $files[array_rand($files)];
include($random_file);

This will handle any .html file, regardless of holes in the numbering sequence, or even if they're numbered at all.

Marc B
  • 356,200
  • 43
  • 426
  • 500