How to get random image from directory using PHP

前端 未结 10 1724
我寻月下人不归
我寻月下人不归 2020-12-02 19:16

I have one directory called images/tips.

Now in that directory I have many images which can change.

I want the PHP script to read the directory, to find the

相关标签:
10条回答
  • 2020-12-02 19:51

    Load folder with images:

    $folder = opendir(images/tips/);
    

    Build table out of files/images from directory:

    $i = 0;
    while(false !=($file = readdir($folder))){
    if($file != "." && $file != ".."){
        $images[$i]= $file;
        $i++;
        }
    }
    

    Pick random:

    $random_img=rand(0,count($images)-1);
    

    Show on page:

    echo '<img src="images/tips'.$images[$random_img].'" alt="" />';
    

    Hope it helps. Of course enclose it in <?php ?>.

    0 讨论(0)
  • 2020-12-02 19:52
    $images = glob('images/tips/*');
    return $images[rand(0, count($images) - 1)];
    

    However, this doesn't ensure that the same image isn't picked twice consecutively.

    0 讨论(0)
  • 2020-12-02 19:58
    $folder = "images";
    $results_img_arr = array();
    if (is_dir($folder))
    {
            if ($handle = opendir($folder))
            {
                    while(($file = readdir($handle)) !== FALSE)
                    {
                        if(!in_array($file,array(".","..")))
                            $results_img_arr[] = $folder."/".$file;
                   }
             closedir($handle);
            }
    }
    $ran_img_key  = array_rand($results_img_arr);
    
    $img_path = $results_img_arr[$ran_img_key];
    
    0 讨论(0)
  • 2020-12-02 20:01
    function get_rand_img($dir)
    {
        $arr = array();
        $list = scandir($dir);
        foreach($list as $file)
        {
            if(!isset($img))
            {
                $img = '';
            }
            if(is_file($dir . '/' . $file))
            {
                $ext = end(explode('.', $file));
                if($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG')
                {
                    array_push($arr, $file);
                    $img = $file;
                }
            }
        }
        if($img != '')
        {
            $img = array_rand($arr);
            $img = $arr[$img];
        }
        $img = str_replace("'", "\'", $img);
        $img = str_replace(" ", "%20", $img);
        return $img;
    }
    
    
    echo get_rand_img('images');
    

    replace 'images' with your folder.

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