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>');
?>
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 ("/")
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'];
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 .
Related
I have a question about how I can access the value from a variable from one page on another one.
I have a registration script and the registration form is on my homepage. I want to dynamically create a random name for every input field (change the value of the name attribute). The current name attribute for the input is just firstName, but I want it to be like firstName_345635. The 345635 is a randomly generated number and will change everytime the page refreshes.
Here is my random number variable:
$firstNameInputName = 'firstName_' . rand(10000, 50000);
The output becomes: firstName_[randomNumer].
The problem is, the register.php has all the post variables to get the form data. What I have now is this:
$firstName = $_POST["firstName"]);
I need to get the value from the random number variables from the homepage and instead of giving the $firstname variable the name firstName, it should get the name that the random number generating variable has produced on the homepage.
How can I achieve this?
You should use a session (or cookies) var to save this dynamic name.
Approach 1. Session (or cookies)
page1.php
<?php
session_start();
$customCode = rand(5, 15);
$_SESSION['customCode'] = $customCode; ?>
<form action="page2.php" method="post">
<input type="text" name="firstName_<?php echo $customCode; ?>" />
</form>
page2.php
<?php
session_start();
$customCode = $_SESSION['customCode']; ?>
$firstName = $_POST['firstName_'.$customCode];
Approach 2. You can put a input hidden field in your form like:
<input type="hidden" name="customCode" value="345635" />
And get it in second page like:
$firstName = $_POST['firstName_'.$_POST['customCode']];
Approach 3. You can iterate over your $_POST array to get firstName like:
foreach($_POST in $key => $value) {
if(strpos($key, "firstName")) {
$firstName = $value;
}
}
The solution is sessions, session variables are superglobal variables which means you can use them in different files as long as its the same session, to use them you need to start the session at every page you'll use them in, also, starting the session has to be done before any output is shown.
Ex (registeration page):
<?php
session_start();
/**
** HTML AND FORM HERE WHATEVER ELSE YOU NEED TO DISPLAY
**/
$_SESSION['FirstName'] = $firstNameInputName;
?>
Ex (processing page):
<?php
session_start();
echo $_POST[$_SESSION['FirstName']]; // Output: Whatever was entered inside the field
?>
How do I maintain the $post value when a page is refreshed; In other words how do I refresh the page without losing the Post value
This in not possible without a page submit in the first place! Unless you somehow submitted the form fields back to the server i.e. Without Page Refresh using jQuery etc. Somesort of Auto Save Form script.
If this is for validation checks no need for sessions as suggested.
User fills in the form and submits back to self
Sever side validation fails
$_GET
<input type="hidden" name="first"
value="<?php echo htmlspecialchars($first, ENT_QUOTES); ?>" />
validation message, end.
alternatively as suggested save the whole post in a session, something like this, but again has to be first submitted to work....
$_POST
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }
You can't do this. POST variables may not be re-sent, if they are, the browser usually does this when the user refreshes the page.
The POST variable will never be re-set if the user clicks a link to another page instead of refreshing.
If $post is a normal variable, then it will never be saved.
If you need to save something, you need to use cookies. $_SESSION is an implementation of cookies. Cookies are data that is stored on the user's browser, and are re-sent with every request.
Reference: http://php.net/manual/en/reserved.variables.session.php
The $_SESSION variable is just an associative array, so to use it, simply do something like:
$_SESSION['foo'] = $bar
You could save your $_POST values inside of $_SESSION's
Save your all $_POST's like this:
<?php
session_start();
$_SESSION['value1'] = $_POST['value1'];
$_SESSION['value2'] = $_POST['value2'];
// ETC...
echo "<input type='text' name='value1' value='".$_SESSION['value1']."' />";
echo "<input type='text' name='value2' value='".$_SESSION['value2']."' />";
?>
Actually in html forms it keeps post data.
this is valuble when you need to keep inserted data in the textboxes.
<form>
<input type="text" name="student_name" value="<?php echo
isset($_POST['student_name']) ? $_POST['student_name']:'';
?>">
</form>
put post values to session
session_start();
$_SESSION["POST_VARS"]=$_POST;
and you can fetch this value in another page like
session_start();
$_SESSION["POST_VARS"]["name"];
$_SESSION["POST_VARS"]["address"];
You can use the same value that you got in the POST inside the form, this way, when you submit it - it'll stay there.
An little example:
<?php
$var = mysql_real_escape_string($_POST['var']);
?>
<form id="1" name="1" action="/" method="post">
<input type="text" value="<?php print $var;?>"/>
<input type="submit" value="Submit" />
</form>
You can use file to save post data so the data will not will not be removed until someone remove the file and of-course you can modify the file easily
if($_POST['name'])
{
$file = fopen('poststored.txt','wb');
fwrite($file,''.$_POST['value'].'');
fclose($file);
}
if (file_exists('poststored.txt')) {
$file = fopen('ipSelected.txt', 'r');
$value = fgets($file);
fclose($file);
}
so your post value stored in $value.
I have a form when the user types something in, it will appear on the screen. I kept the text that the user typed in a variable called $output, then I tried to put each $output into an array called $arrayText, my objective is to have the user type in something and click a button, then the user's text appears on the screen and when he tries for the second time, the first text is still there while the new one will be on the next line. However, it works only for the first time. For the second time, it replaces the second text with the old one, here is my code
if (isset($_POST['putContents'])) {
$output = $_POST['contents'];
test();
}
function test()
{
static $arrayText = array();
global $output;
$arrayText[]= $output;
for($i = 0; $i < count($arrayText); $i++){
echo $arrayText[$i];
echo "<br>";
}
}
}
?>
thanks for any help in advance
You can't "collect" the user input line-by-line into an array after each time he presses the submit button. The lines must be persisted (stored) somewhere. You can store each line as a record in a database or in a session cookie as suggested. I would persist the state by storing the entered lines in hidden input tags inside your form:
<input type="hidden" name="line[0]" value="What the user typed in first" />
<input type="hidden" name="line[1]" value="The second line that was typed in" />
<input type="text" name="contents" value="" />
By executing a second time your script your $_POST will only have the values of your last submit which in your case will override your array.
If you want to store data beyond the current process you'll have to store the date somewhere other then the $_POST global.
I'm suggesting you use sessions for this as a database query would certainly over blow your needs.
Use:
session_name("admin");
session_start();
if(empty($_SESSION["yourOldText"])) $_SESSION["yourOldText"]=$_POST["userinput"];
and if you want to access your old data then you can just use $_SESSION["yourOldText"]
When I post my form data:
<form action="layouts.php" method="post">
<input type="text" name="bgcolor">
<input type="submit" value="Submit" align="middle">
</form>
to a php page, "layouts.php", it returns the string, as expected.:
$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"
But when I include "layouts.php" in another page it returns NULL.
<?php
include("php/layouts.php");
echo $bgcolor; //
echo gettype($bgcolor); //returns "NULL"
?>
How do I pass the variable to another page?
You'll have to use a session to have variables float around in between files like that.
It's quite simple to setup. In the beginning of each PHP file, you add this code to begin a session:
session_start();
You can store variables inside of a session like this:
$_SESSION['foo'] = 'bar';
And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions).
layouts.php
<?php
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>
new.php
<?php
session_start();
echo $_SESSION['bgcolor'];
?>
Give the form two action="" and see what happens. I just tried that on a script of mine and it worked fine.
A more proper way to solve this might exist, but that is an option.
ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.