开发者

Reuse PHP image randomizer

开发者 https://www.devze.com 2023-02-13 03:56 出处:网络
I wrote a simple image randomizer on PHP that picks a random image from a list using the rand() function. The code works perfectly, and a random image is generated when I include it on my html as a pi

I wrote a simple image randomizer on PHP that picks a random image from a list using the rand() function. The code works perfectly, and a random image is generated when I include it on my html as a picture.

The problem comes when I try to include it twice in the same html. A random image WILL be generated and displayed for both times I included it, but it will be the same image. In other words, I get a repeated random image on my page.

An easy way to solve this is to simply copy the randomizer.php, give it a new name, and include both images in HTML. The reason I don't want to do this is because my final HTML will have about 25 pictures, and I simply开发者_StackOverflow feel like there should be a better way to do this. Keep in mind that I CANNOT add any PHP functions into my HTML, given that my files are hosted in different servers, and my HTML server does not support PHP.

If anyone know of a better fix other than creating 25 copies of my randomizer.php file (or creating 25 different files that include it), please let me know. I will most definitely appreciate your input!!

Thank you very, very much!!

Here's a snippet of the code:

if (count($fileList) > 0) {
    do { //do-while loop will get a new random image until that image has not been used yet in this session
        $imageNumber = rand( 0 , ( count($fileList) - 1) ); //get random image from fileList
        $iterations++;
    } while( !(empty($_SESSION['img' . $imageNumber])) && iterations < 200);

    $_SESSION['img' . $imageNumber] = True; //this image number has been displayed

    $_SESSION['shown']++; //increments the number of shown pictures in this signature

    $img = $folder.$fileList[$imageNumber];
}


It may be that the browser thinks it is the same image and is caching, try setting the name of the image (emit a header with content-disposition/filename IIRC) and/or adding a unique tag to the end of the image name with a random string, ( e.g. image.jpg?e0.6613725793930488 )


My guess is that rand() either didn't reseed, or is seeded with the same value. Have you considered calling srand() - or "the better random number generator" combination of mt_srand() and mt_rand()?

0

精彩评论

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