Search code examples
phpsessionechosession-cookiesshuffle

How to apply php user session to random quote snippet?


Still learning PHP and trying to apply a user session snippet to my quote snippet so that it doesn't shuffle on every user page re-load.

Here is the working session code being applied to a different random quote snippet: php - keep value that is shuffled even if page is refreshed

How do I properly apply the session code from the above URL answer to my PHP quote code here? Spent 2 hours now trying to apply the session code in the above link to this snippet but just cant get it right!

<?php 
$r_array=file('quotes.txt'); 
shuffle($r_array); 
echo $mQuotePath[0]; 
echo $r_array[0]; 
?>

I also checked out the PHP session tutorial here but I am still lost. Would someone be so kind in showing me how this is done? Thanks so much!


Solution

  • Is this what you're looking for?

    <?php 
    session_start();
    
    if(!isset($_SESSION['shuffled_array'])){
        $_SESSION['shuffled_array'] = shuffle(file('quotes.txt')); 
    }
    $r_array=$_SESSION['shuffled_array']; 
    // echo $mQuotePath[0]; // Not sure where you're getting this variable from but it doesn't seem to be declared
    echo $r_array[0]; 
    ?>