Select random file from directory

后端 未结 4 1278
深忆病人
深忆病人 2020-11-30 04:43

I\'m trying to make a site where users can submit photos, and then randomly view others photos one by one on another page. I have a directory called \"uploads\" where the pi

相关标签:
4条回答
  • 2020-11-30 05:10

    I've turned it a little to get more than one random file from a directory using array.

    <?php
    
    function random_pic($dir)
    {
     $files = glob($dir . '/*.jpg');
     $rand_keys = array_rand($files, 3);
     return array($files[$rand_keys[0]], $files[$rand_keys[1]], $files[$rand_keys[2]]);
    }
    
    // Calling function
    
    list($file_1,$file_2,$file_3)= random_pic("images"); 
    
    ?>
    

    You can also use loop to get values.

    0 讨论(0)
  • 2020-11-30 05:19

    Or you can use opendir() instead of glob() because it's faster

    0 讨论(0)
  • 2020-11-30 05:22

    This single line of code displays one random image from the target directory.

    <img src="/images/image_<?php $random = rand(1,127); echo $random; ?>.png" />
    

    Target directory: /images/

    Image prefix: image_

    Number of images in directory: 127

    https://perishablepress.com/drop-dead-easy-random-images-via-php/


    Drawbacks

    • images must be named sequentially (eg image_1.png, image_2.png, image_3.png, etc).

    • you need to know how many images are in the directory in advance.


    Alternatives

    Perhaps there's a simple way to make this work with arbitrary image-names and file-count, so you don't have to rename or count your files.

    Untested ideas:

    • <img src=<?php $dir='/images/'; echo $dir . array_rand(glob($dir . '*.jpg')); ?> />

    • shuffle()

    • scanDir() with rand(1,scanDir.length)

    0 讨论(0)
  • 2020-11-30 05:28

    You can use glob to get all files in a directory, and then take a random element from that array. A function like this would do it for you:

    function random_pic($dir = 'uploads')
    {
        $files = glob($dir . '/*.*');
        $file = array_rand($files);
        return $files[$file];
    }
    
    0 讨论(0)
提交回复
热议问题