Search code examples
phpfunctionvariablesgettext-files

How to keep variable constant even after page refresh in PHP


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>');
?>

Solution

  • use sessions:

    session_start();   // in top of PHP file
    ...
    $_SESSION["word"] = choose_word($words);
    

    $_SESSION["word"] will be there on refresh

    if you care about the "lifetime", follow also this (put it just before session_start)

    session_set_cookie_params(3600,"/");
    

    It will hold an hour for the entire domain ("/")