How to save a constant variable even after refreshing a page in PHP

I am making a simple hangman application and I have a php file and a separate .txt file containing words, one on each line.

I want the $ word variable to remain constant even after the page has been refreshed, since I planned to use GET or POST to enter the user.

In the code example below, I want $ word to stay the same after submitting the form. I believe this is a simple question about moving the code to another place, but I cannot figure out what 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>'); ?> 
+4
source share
2 answers

use sessions:

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

$_SESSION["word"] will be present when updating

if you care about "life", follow this as well (put it before session_start )

 session_set_cookie_params(3600,"/"); 

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

+6
source

You can use 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 can use PHP $ _ COOKIE , which can be called forever (but it seems to be a waste if you just want it on the next page):

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

... and on the next page:

 echo $_COOKIE['word']; 
0
source

Source: https://habr.com/ru/post/1479047/


All Articles