php 即使在PHP中刷新页面后如何保持变量不变
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16365555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep variable constant even after page refresh in PHP
提问by JeanBeanie
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.
我正在制作一个简单的刽子手应用程序,我有我的 php 文件和一个单独的 .txt 文件,其中包含单词,每行一个。
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.
我想要的是 $word 变量即使在页面刷新后也保持不变,因为我计划使用 GET 或 POST 来获取用户的输入。
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!
在下面的示例代码中,我希望 $word 在提交表单后保持不变。我相信将代码移动到另一个地方是一件简单的事情,但我不知道在哪里可以为这个 PHP 菜鸟提供任何帮助!
wordsEn1.txt:
wordsEn1.txt:
cat
dog
functions.php:
函数.php:
<?php
function choose_word($words) {
return trim($words[array_rand($words)]);
}
?>
hangman.php:
刽子手.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>');
?>
回答by
use sessions:
使用会话:
session_start(); // in top of PHP file
...
$_SESSION["word"] = choose_word($words);
$_SESSION["word"]
will be there on refresh
$_SESSION["word"]
将在那里刷新
if you care about the "lifetime", follow also this (put it just before session_start
)
如果你关心“生命周期”,也请遵循这个(把它放在前面session_start
)
session_set_cookie_params(3600,"/");
It will hold an hourfor the entire domain ("/")
整个域(“/”)将保持一个小时
回答by John Smith
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):
或者你可以使用一个 PHP $_COOKIE,它可以被永远调用(但如果你只想要它在下一页,那就有点浪费了):
setcookie('word', $word, time()+3600, '/');
...and on the next page:
...在下一页:
echo $_COOKIE['word'];
回答by Ram
Just use hidden type forms for that issue.if we put it into session while page refreshes its hide also. if you can store that value in hidden form field it was stored and retrived any time .
只需为该问题使用隐藏类型的表单。如果我们将其放入会话中,同时页面也会刷新其隐藏。如果您可以将该值存储在隐藏表单字段中,则它可以随时存储和检索。