Get the value of a variable in page1.php in page2.php - php

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
?>

Related

How to retain the values in an array when submit button is clicked [duplicate]

This question already has answers here:
PHP Pass variable to next page
(9 answers)
Closed 8 years ago.
php newbie here. How do I retain the value of an array when I click the submit button? So this how the program works. The user will input a name and a seat number(between 1-25) and when the the user clicks submit button, the name will be added on the array and will be displayed on the table. It works for the first input but when i entered another name and seat number, the first input is deleted. Please help.
//this is where the user will input...
Student Name: <input type="text" name="name" id="name"><br>
Seat Number: <input type="text" name="seat" id="seat"><br>
<input type="submit" name="assign" value="Assign"> <?php echo $warning; ?>
//and this is my php code.
<?php
$students = array_fill(0, 25, NULL);//this is to make an empty array with the size of 25.
if(isset($_POST['assign'])){
$student = $_POST['name'];
$seat = $_POST['seat'];
if($seat > 25 || $seat < 1){
$warning = 'Seat number does not exist.';
}
else{
$warning = '';
$students[$seat-1] = $student;
}
}
?>
//This code here is just a part of the HTML code for the table. this is where the name will display.
<td id="box"><?php echo $students[0]; ?></td>
<td id="box"><?php echo $students[1]; ?></td>
<td id="box"><?php echo $students[2]; ?></td>
<td id="box"><?php echo $students[3]; ?></td>
<td id="box"><?php echo $students[4]; ?></td>
Because every time you click on submit button,the $students array is created again and again and therefore you lose the previous values which the $students was holding.So create your array only once while submitting your form the first time.
EDIT: alternative: use php SESSION for this(just one of the many alternatives)
Before you can store user information in your PHP session, you must first start up the session.
<?php session_start(); ?>
<html>
<body>
</body>
</html>
And then you can store or retrieve anything in the session by manipulating $_SESSION array in php.So instead of storing seat no.s in a normal php variable you can use $_SESSION.Just keep everything the same(ie method="post" etc etc) and instead of $students use $_SESSION["students],where students will be an array in the $_SESSION(and it will remain there till your session expires ie till user logs out or closes the page in your case)
See here for more example: http://www.w3schools.com/php/php_sessions.asp
Use sessions like this:
<?php
session_start(); // To start the session, must be called before trying to manipulate any session variables. Preferably the first php-line on each page who will use sessions.
$_SESSION['students'] = array_fill(0, 25, NULL); // Sets an array of 25 indexes to session variable 'students'
?>
The code block above should not be called each time the user clicks submit - it should only be called once.
<?php
session_start();
if(isset($_POST['assign'])){
$student = $_POST['name'];
$seat = $_POST['seat'];
if($seat > 25 || $seat < 1){
$warning = 'Seat number does not exist.';
}
else{
$warning = '';
$_SESSION['students'][$seat-1] = $student; // Sets index [$seat-1] of array to $student
}
}
?>
Session variables are stored temporarily on the server and can be accessed throughout the website as long as you remember to start the session on each page (as shown in the code).
As Anmol said before, read more about sessions here: http://www.w3schools.com/php/php_sessions.asp
Edit:
<?php
session_start(); // To start the session, must be called before trying to manipulate any session variables. Preferably the first php-line on each page who will use sessions.
if(!isset($_SESSION['students'])){
$_SESSION['students'] = array_fill(0, 25, NULL); // Sets an array of 25 indexes to session variable 'students'
}
?>

Session variable persist through POST

Can anyone see a bug in my code here?
Two files, one variable is set on the first page using JS and I want to pass it to the next page.
username variable is set here, first in variable then in session
username = wordOne + wordTwo + wordThree;
<?php $_SESSION['username'] = $username; ?>
then I submit the form which takes user to register-form.php
<form method="POST" action="register-form.php">
<button>I like it! Make it my username.</button>
</form>
when that page loads, username is grabbed and output into the input as a value
<body onload="inputUsername()">
function inputUsername(){
var username = "<?php echo isset($_POST[username])?$_POST[username]:''; ?>";
console.log("I'm running " + username);
document.getElementById('inputUsername').value = username;
}
But this doesn't work as the variable username is not persisting across the pages.
What I see is that you are asking for $_POST[username] but from the form you're not passing it.I mean something like this:
<form method="POST" action="register-form.php">
<input type="hidden" name="username" value="<?php echo $_SESSION['username']; ?>">
<button>I like it! Make it my username.</button>
In your current code, You are accessing _POST variable, however you are setting _SESSION variable in your code. Therefore, the possible fix is :
1. check for _SESSION variable in inputUsername() function OR
2. Set username in your form, so that when you submit it, it post to new page.

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

Refresh page without losing the Post value

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.

PHP quiz send data to next page

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.

Categories