php generate random image from a directory

后端 未结 4 1285
轻奢々
轻奢々 2020-12-21 09:49

I have to generate random image from a directory. I know which is simple like,

   $dire=\"images/\";
   $images = glob($dire. \'*.{jpg,jpeg,png,gif}\', GLOB_         


        
相关标签:
4条回答
  • 2020-12-21 09:56

    One solution might be to do this:

    <?
    // initialize $images
    shuffle($images);
    $randomImage = array_pop($images);
    ?>
    <input type="image" src="<?=$randomImage;?>" alt="<?=$randomImage;?>" />
    

    This will guarantee that you use each image only once, in a random order.

    0 讨论(0)
  • 2020-12-21 10:02

    These codes helps to pull random images from folder

           <?php 
                $files = glob('photos/*'); 
                   natcasesort($files);      // Display images  
                foreach($files as $file) {     
                   echo '<img src="' . $file . '"/>';
                }  
            ?>
    
    0 讨论(0)
  • 2020-12-21 10:03

    Here's my answer, which seems to work OK. It produces one image generated randomly from the images in a given folder:

    <?php 
    $result = glob('images/*'); 
    shuffle($result);
    foreach($result as $result) {     
       break;     
    }  
    ?>
    <img src="<?php echo "$result"; ?>" />
    
    0 讨论(0)
  • 2020-12-21 10:19

    One alternative to array_rand is shuffle:

    $dire="images/";
    $images = glob($dire. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    shuffle($images);
    

    And then to display the next random image:

    $randomImage=array_pop($images);
    

    When the array is empty you call the initialization code again. So putting it together:

    $images=array()  //Initialize once at top of script
    $dire="images/";
    ...
    if(count($images)==0){
      $images = glob($dire. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
      shuffle($images);
      }
    $randomImage=array_pop($images);
    

    (I deliberately repeated the glob() so that any new images get discovered on the second iteration.)

    P.S. I'm assuming you understand that, by default, PHP is stateless. If this is supposed to give each user a different image each time they visit a page (e.g. a rotating banner ad), then the code is almost the same, but move the $images array into $_SESSION.

    0 讨论(0)
提交回复
热议问题