php form action handler and save it - php

i am trying to make a page for form action handler using php
the the problem is that i want the action to be saved on that page
here's my form on index.php
<form method="get" onSubmit="return val()" action="han.php">
<label>Name:</label>
<input type="text" id="name" name="name" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
and here's my php code on han.php
<?php
$name = $_GET['name'];
echo "Your Name is:".$name;
?>
i need that name to be saved on han.php file like this every time i submit a name:
Your Name is: Brian
Your Name is: Jack
Your Name is: Daniel
Your Name is: Bob

What you can do is to create another file for saved names for example names.txt then in your han.php you could write this to save the name each time the form is submitted:
<?php
$name = $_GET['name'];
$file = fopen("names.txt","a");
echo fwrite($file,"$name, \n");
fclose($file);
return header('Location: index.php'); // to redirect to index.php page
?>

You can save them in the current session
<?php
session_start();
if(!isset($_SESSION['names']))
$_SESSION['names'] = array();
if(isset($_GET['name']))
array_push($_SESSION['names'], $_GET['name']);
if(isset($_SESSION['names']))
foreach($_SESSION['names'] as $name)
echo $name."<br>";
?>

It is not fully clear, what you mean by save, but here are some possible solutions:
1. Every name schould be saved "for ever" (big amount of names expected):
Use a Database like MySQL (see here)
2. The current name should be saved for a period of time:
Use session variables for this case
if(!isset($_SESSION['name']) {
$_SESSION['name'] = $_GET['name'];
$_SESSION['name'] = date();
}
you can also check befor this, if a period of time has expired and overwrite the name variable.
3. One or more names should be saved for all calls of the script (from any user):
You can use a file and save the names in this file:
create and write to file
read from file OR get whole file (file_get_contents)

Related

Can php session variable be changed, and if so how?

I am totally confused with session variables. I thought that if I set a session variable, then that variable will be available in any php document that begins with session_start. But it's not working.
Form:
<?php
session_start();
if(isset($_POST['hour'])) {
$_SESSION['hour'] = $_POST['hour'];
}
?>
<!DOCTYPE html>
<html>
<body>
<form action='viewA.php' method='post'>
<input type="text" name='hour' value='24'>
<input type ='submit' name= 'submit' value='submit'>
</form>
</body>
</html>
I post to viewA.php, and it works:
<?php
$hour = $_POST['hour'];
echo 'I am view A, and hour is '.$hour;
?>
<html>
<a href='View_B.php'>See View B</a>
<a href='TEST_form.php' >Choose another hour</a>
</html>
The file viewA.php has a link to View_B.php; here's View_B's code:
<?php
session_start();
print_r($_SESSION);
//$hour = $_SESSION['hour'];
//echo '... and in view B, hour is '.$hour;
?>
<html>
<a href='aatestform.php' >Choose another hour</a>
</html>
No matter what I put into the input in the form, the print_r($_SESSION); View_B outputs only Array ( [hour] => 13 ), which is the first hour I chose way back when. I type in "22"; it outputs 13. I type in "08", it outputs 13.
According to w3schools, "To change a session variable, just overwrite it"
What am I doing wrong? Please help!
In your viewA.php you don't store / overwrite the session variable with the $_POST value.
You just do it in your TEST_form.php which doesn't get any $_POST so your if(isset(... is useless.
Your post destination (the action) is viewA.php, this means that your request will be made to viewA.php.
You're using session variabiles only in the form page and in View_B.php.
If you look carefully at your code in ViewA.php, you'll see that you're working only with POST variables, not session variables.
This php code, that you have in your form page
<?php
session_start();
if(isset($_POST['hour'])) {
$_SESSION['hour'] = $_POST['hour'];
}
?>
Should be moved to viewA.php.
Doing this, viewA.php will check if the POST variable "hours" is set. In that case, it overwrite (or create) the session variable "hours".

How to trigger execution of a PHP file within a PHP file

So I have an HTML file that is a basic form. Say
<form method="POST" action="test1.php">
Name: <input type="text" name="name" id="name" />
<input type="submit" value="Submit" />
</form>
Now I have that execute my test1.php file which goes as follows:
<?php
$name = $_POST['name'];
?>
So all it is doing is getting the value from the HTML form. Now I have a second PHP file test2.php that needs to get the value from the first test1.php file $name and output it via an echo statement.
I'm new to PHP and am fine with using one PHP file to output values from an HTML form, but I don't know how to approach a second one.
I'm aware that you can use the include statement to carry over the variables and their values, but it didn't seem to work in my instance. I'm almost positive the issue is that I don't have test2.php actually being executed. And I don't know how to approach that. Any help is appreciated.
EDIT: This is all I want test2.php to do. $name has to be the same value as retrieved from the HTML form in test1.php
<?php
echo $name;
?>
Just use include your file test2.php inside test1.php:
<?php
$name = $_POST['name'];
include('test2.php');
?>
Whenever you include a file using either include() or require(), the file always gets "executed", so maybe there's something else wrong in you code.
EDIT
test1.php:
<?php
$name = $_POST['name'];
include('test2.php');
?>
test2.php:
<?php
echo $name;
?>
I would suggest starting a session in test1, assign the var $name to the session and then picking the session up on test2.
test1.php
session_start();
$name = filter_var($_POST['name'],FILTER_SANITIZE_STRING);
$_SESSION['test1']['name'] = $name;
test2.php
session_start();
$name = $_SESSION['test1']['name'];
Try that.
#bloodyKnuckles, Your assignment was left open ended because there are a number of ways you can accomplish what you're looking to do.
include('test2.php');
Is one option. Another would be
header("Location: test2.php");
exit();
Using the header option, $_SESSION variable would work. If test1.php had any HTML output, you could consider an AJAX call or urlencode() your string.
test1.php
echo 'Click Me';
test2.php
$name = $_GET['name'];
I'm guessing your assignment task was designed to demonstrate various ways to pass values from script to script.
Good Luck

Get the value of a variable in page1.php in page2.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
?>

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.

Categories