How to keep variable constant even after page refresh in PHP

31,193

You could use a hidden input:

<form method="POST">
    <input type="text" />
    <input type="hidden" name="word" value="<?php echo $word; ?>" />
</form>

...and on the next page:

if(isset($_POST['word'])) {
    echo $_POST['word'];
}

Or you could use a PHP $_COOKIE, which can be called forever (but kind of a waste if you just want it on the next page):

setcookie('word', $word, time()+3600, '/');

...and on the next page:

echo $_COOKIE['word'];
Share:
31,193
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm making a simple hangman application and I have my php file and a separate .txt file holding the words, one on each line.

    What I want is for the $word variable to remain constant even after the page refreshes since I was planning on using a GET or POST to get the user's input.

    In the example code below I want $word to stay the same after the form is submitted. I believe it's a simple matter of moving code to another place but I can't figure out where any help for this PHP noob would be appreciated!

    wordsEn1.txt:

    cat
    dog
    

    functions.php:

    <?php
    
    function choose_word($words) {
        return trim($words[array_rand($words)]);
    }
    ?>
    

    hangman.php:

    <?php
    include('functions.php');
    
    $handle = fopen('wordsEn1.txt', 'r');
    $words = array();
    
    while(!feof($handle)) {
    $words[] = trim(fgets($handle));
    }
    
    $word = choose_word($words);
    
    echo($word);
    echo('<form><input type="text" name="guess"></form>');
    ?>
    
  • Admin
    Admin about 8 years
    This will not work if the user presses F5 to refresh.