jeudi 14 décembre 2017

random image in php and cookies

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"] . "
    "; $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.




Aucun commentaire:

Enregistrer un commentaire