0

I have to create a real random image script for a webpage. There are thousands of pictures available, but the solution I provided is was not accepted, because visitors got very often the same images.

This is my current code (which is working but not really random) :

$RandBG = sprintf('%04d', (random_int(1, NbBackgroudImages)));

NbBackgroudImages is the constant containing the number of images, for examples 2798 in my case.

Now, the idea to optimise the random image, I am thinking of using cookies.

The idea is as follows :

  1. Show a random background
  2. Place a cookie with that background number
  3. If user comes back, 1st check if there is a cookie, if yes, then check which number.
  4. Then loop thru the available images excluding the image number in the cookie(s)
  5. If the cookie total images amounts to the total number of available images (user has seen all images) then restart at step one.

This is what I have done so far and I think I'm over killing it...

Any suggestion or input is welcome :

  1. I create an array with all the available images.

    for ($x = 1; $x <= NbBackgroudImages; $x++) {
        $RandBGx    = sprintf('%04d', ($x));
        $arrayBG[]  = $RandBGx;
    }
    $AllBG = implode(',', $arrayBG);
    
  2. I loop thru the available images and set my cookies for each image (maybe could be optimised...)

    for ($x = 1; $x <= NbBackgroudImages; $x++) {
        $RandBGx = sprintf('%04d', ($x));
    
        if( isset($_COOKIE["RandBG_$RandBGx"])){ // I set the cookie with the img number
            $found = 1;
            //echo "LAST IMAGE " . $_COOKIE["RandBG_$RandBGx"] . "<br />";
            $array[] = $RandBGx;
            $ExcludedBG = implode(',', $array);
            //echo $ExcludedBG;
            $result = array_diff($array,$arrayBG);
            $NextBG = implode(',', $result);
        }else{
            if(empty($found)){
                //echo "No cookie found";   
                setcookie("BG_$RandBG", "$RandBG", time() + (86400 * 30), "/","", 0);
            }
        }
    } 
    

This is where I have a problem, I am trying to use 'array_diff' to see which number in the array are not in the first array.

But I'm getting confused and I'm not getting the result that I need.

Thank you for any help.

* UPDATED * I found the solution myself. This is what I will use until I find something better :

define('NbBackgroudImages', 5);
define('CookieName', "testcookie");

// SETTING FIRST RANDOM IMAGE
$RandBG = sprintf('%04d', (random_int(1, NbBackgroudImages)));

for ($x = 1; $x <= NbBackgroudImages; $x++) {
    $RandBGx        = sprintf('%04d', ($x));
    $arrayAllBG[]   = $RandBGx;
}
$AllBG = implode(',', $arrayAllBG);

echo "LISTING ALL ARRAY VALUES: $AllBG <br>";

if( isset($_COOKIE[CookieName.$RandBG])){
    echo "I FOUND A COOKIE : ".$_COOKIE[CookieName.$RandBG]."<br>";
    // SET A NEW ARRAY WITH COOKIE VALUES
    //$arrayBGx[] = $RandBGx;
    //LOOPING THRU AVAILABLE IMAGES
    foreach ($_COOKIE as $key=>$val){
        echo $key.' is '.$val."<br>\n";
        // SET A NEW ARRAY WITH COOKIE VALUES
        $arraySeenBG[] = $val;
    }
    // ARRAY WITH EXCLUDED IMAGES
    $ExcludedBG = implode(',', $arraySeenBG);
    echo "I SHOULD NOT SHOW THESE : $ExcludedBG <br>";

    //FIND THE MISSING NUMBERS IN BOTWH ARRAYS
    $ArrayNextUnseenBG  = array_diff($arrayAllBG,$arraySeenBG);
    $NbAvailableElement = count($ArrayNextUnseenBG);
    echo "I HAVE $NbAvailableElement TO CHOOSE FROM <BR>";
    if(!empty($NbAvailableElement)){
    //  I STILL HAVE UNSEEN IMAGES  
        $NextUnseenBG       = implode(',', $ArrayNextUnseenBG);
        echo "I CAN SHOW THESE (NEVER SEEN BEFORE) : $NextUnseenBG <br>";

        if($NbAvailableElement == 1){
        // IF I ONLY HAVE ONE VALUE IT'S NOT AN ARRAY ANYMORE AND SHOULD SHOW THAT REMAINING ONE
            echo "I ONLY HAVE ONE TO SHOW : $NextUnseenBG<br>";
            $RandBG = $NextUnseenBG;
            echo "---> $RandBG <br>";
            setcookie(CookieName.$RandBG, "$RandBG", time() + (86400 * 30), "/","", 0);
            echo "SET A NEW COOKIE WITH RANDOM ABOVE NEW RANDOM VALUE <BR>";
        }else{
            echo "I HAVE MORE THAN ONE TO SHOW <BR>";
            $RandBGx = array_rand(array_flip($ArrayNextUnseenBG), $NbAvailableElement);

            // SHOWING ALL AVAILABLE VALUES IN ARRAY
            print_r(array_values($RandBGx));

            $RandBG = $RandBGx['0'];
            echo "I WILL SHOW THIS ONE : $RandBG<br>";

            setcookie(CookieName.$RandBG, "$RandBG", time() + (86400 * 30), "/","", 0);
            echo "SET A NEW COOKIE WITH RANDOM ABOVE NEW RANDOM VALUE <BR>";
        }
    }else{
    // I HAVE SEEN ALL THE IMAGES - DELETING ALL COOKIES AND STARTING OVER
        echo "I HAVE SEEN ALL IMAGES <BR> DELETING COOKIES AND STARTING OVER <BR>";
        for ($x = 1; $x <= NbBackgroudImages; $x++){
            $RandBG = sprintf('%04d', ($x));

            if(isset($_COOKIE[CookieName.$RandBG])){
                unset($_COOKIE[CookieName.$RandBG]);
                setcookie(CookieName.$RandBG, null, -1, '/');
                echo "DELETING OK FOR THIS ONE".CookieName.$RandBG."<BR>";
            }else{
                echo "DELETING FAILED FOR THIS ONE ".CookieName.$RandBG."<BR>";
            }
        }
        $RandBG = sprintf('%04d', (random_int(1, NbBackgroudImages)));
        setcookie(CookieName.$RandBG, "$RandBG", time() + (86400 * 30), "/","", 0);
    }

}else{
    // SETTING THE COOKIE
    setcookie(CookieName.$RandBG, "$RandBG", time() + (86400 * 30), "/","", 0);
    echo "I DIDN'T FIND A COOKIE - SETTING NEW COOKIE WITH RANDOM VALUE OF : $RandBG <BR>";
}

echo " <br> <br> <br> I'M SHOWING THIS ONE $RandBG <br>";
echo "<img src='img/bg/workspace$RandBG.jpg' height='100'>";
Bryan Meyer
  • 103
  • 13
  • You (or your client?) have a fundamental misunderstanding of what "random" means. It doesn't mean "no duplicates". See the linked thread for clarifications, algorithms to accomplish your *non*-random approach, etc. – ceejayoz Dec 14 '17 at 19:19
  • I don't see how that is supposed to help. It's a minimalist approach. Great, lets have 10 times the same element on the same day with over a few thousands available resources. Don't you think it's a waste ? I will work on my code and update the answer so it may help someone else who thinks that your random minimalisme is not okay. – Bryan Meyer Dec 15 '17 at 11:14
  • The linked thread has plenty of solutions (you seem to want the "shuffle bag" approach) for you. It's just important to note that you say you want "real random" but you're actually asking for the opposite. – ceejayoz Dec 15 '17 at 13:53
  • @ceejayoz thank you, I read, found interesting things. I will go with my updated answer for now. When I will have more time I will try to find a less ressource eating solution. It's a lot of set cookies and a lot of 'if' 'else' conditions just for a random unique background image. Thank you for your input ! – Bryan Meyer Dec 15 '17 at 14:20

0 Answers0