I have three pages. One of which there is a list of texts the user can select. Upon clicking on one of the texts they will be redirected to another page by using:
<a href='second.php?text=whatever>Whatever</a>
A page where they will input the username they wish to send those texts to - using forms. I wish to proceed to the third page with those two variable - texts and username. I only manage to proceed to third page with username only.
I am getting third.php?username=inputtedUsername.
I want to get third.php?username=inputtedUsername&&text=whatever.
I am aware that I can do by storing the text to a SESSION on page two and than transfer it over to third page.
I wish to know if there is another secure way to do this - maybe something needed to be changed in the form action=thirdpage.php? I dont know. Thank you. ö.ö.
Solved: After reading comments and answer, the thing I need was type=hidden. It is now working on my part. Thanks everyone for helping me. :).
'second.php?text=whatever'? You can't just put whatever to the text, you are doing it wrong. Try this.
firstpage.php
<?php
$whatever = 'Tom & Jerry, 1 + 2 = 3';
echo '' . $whatever . '';
?>
secondpage.php
<form action="thirdpage.php" method="post">
<input type="text" name="username" value="" />
<input type="hidden" name="text" value="<?php echo base64_decode($_GET['text']); ?>" />
<input type="submit" value="Submit" />
</form>
thirdpage.php
<?php
echo 'Username: ' . $_POST['username'];
echo '<br />';
echo 'Text: ' . $_POST['text'];
?>
Related
My website involves a user submitting data over several pages of forms. I can pass data submitted on one page straight to the next page, but how do I go about sending it to pages after that? Here's a very simplified version of what I'm doing.
Page 1:
<?php
echo "<form action='page2.php' method='post'>
Please enter your name: <input type='text' name='Name'/>
<input type='submit' value='Submit'/></form>";
?>
Page 2:
<?php
$name=$_POST["Name"];
echo "Hello $name!<br/>
<form action='page3.php' method='post'>
Please enter your request: <input type='text' name='Req'/>
<input type='submit' value='Submit'/></form>";
?>
Page 3:
<?php
echo "Thank you for your request, $name!";
?>
The final page is supposed to display the user's name, but obviously it won't work because I haven't passed that variable to the page. I can't have all data submitted on the same page for complicated reasons so I need to have everything split up. So how can I get this variable and others to carry over?
Use sessions:
session_start(); on every page
$_SESSION['name'] = $_POST['name'];
then on page3 you can echo $_SESSION['name']
You could store the data in a cookie on the user's client, which is abstracted into the concept of a session. See PHP session management.
if you don't want cookies or sessions:
use a hidden input field in second page and initialize the variable by posting it like:
page2----
$name=$_POST['name']; /// from page one
<form method="post" action="page3.php">
<input type="text" name="req">
<input type="hidden" name="holdname" value="<? echo "$name"?>">
////////you can start by making the field visible and see if it holds the value
</form>
page3----
$name=$_POST['holdname']; ////post the form in page 2
$req=$_POST['req']; ///// and the other field
echo "$name, Your name was successfully passed through 3 pages";
As mentioned by others, saving the data in SESSION is probably your best bet.
Alternatly you could add the data to a hidden field, to post it along:
page2:
<input type="hidden" name="username" value="<?php echo $name;?>"/>
page3
echo "hello $_POST['username'};
You can create sessions, and use posts. You could also use $_GET to get variables from the URL.
Remember, if you aren't using prepared statements, make sure you escape all user input...
Use SESSION variable or hidden input field
This is my workaround of this problem: instead of manually typing in hidden input fields, I just go foreach over $_POST:
foreach ($_POST as $key => $value) {
echo '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
}
Hope this helps those with lots of fields in $_POST :)
I've been trying to create a simple little blog for something I want to add in my school assignment. All I want it to do is to output my input in the order it is entered (like a wall on facebook).
My code is:
<?php
//other form that does the password
$pass = $_POST['pass'];
$blog =$_POST['blog'];
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<textarea placeholder="Write Something, Me."
autofocus
required
autocomplete="off"
name="blog"></textarea>
<br />
<input type="password"
placeholder="Password"
autocomplete="off"
name="pass"
method="post" />
<input type="submit"
name="submit"
value="Submit">
</form>
<?php
If ($pass=="pass") {
echo 'Access Confirmed<br>';
echo $blog;
echo '<br/><br/>';
echo $blog;
echo '<br/><br/>';
echo $blog;
} else {
echo 'Wrong password or invalid blog entry. Try again Noob.<br>';
}
?>
I need to be able to call $blog as an array and output multiples datas as they are being entered (like in facebook). But as you can tell it's just printing the same thing over and over again. Also I don't want it do delete all the inputs if the "Password" (can't really call it secure) is entered incorrectly. I still want to be able to see the previous inputs.
I've tried many things, but none seem to work for me.
If this is unclear and you still have questions, please ask. Thanks.
I think you're a long ways from where you want to be with this. I'll get you started by saying that if you have an array, you can't simply use echo to print it, you need to enumerate through the array and print out the pieces that you're interested in.
foreach ($blog as $value) {
echo $value;
}
Start here and work your way up: http://www.php.net/manual/en/control-structures.foreach.php
I've created a registration form that successfully passes its variables from the registration page (go-gold.php) to a summary/verfication page (go-gold-summary.php). The data appears correctly on the second page.
However, I want to able to use an image button to return back to the registration page, in case the user made an entry error. Going back, the original form should now be populated with the data that was first entered.
The problem is that I cannot re-send/return the data from the second page, back to the first. My text fields appear blank. I do NOT want to use Session variables.
The code is truncated from the entire page.
Registration Page (go-gold.php):
<?php
$customer_name = $_POST['customer_name'];
?>
<form action="go-gold-summary.php" method="post">
Name: <input type="text" name="customer_name" id="customer_name" value= "<?php echo $customer_name ?>" />
<input name="<?php echo $customer_name ?>" type="hidden" id="<?php echo $customer_name ?>">
</form>
Summary Page (go-gold-summary.php)
<?php
$customer_name = $_POST['customer_name'];
?>
<form action="go-gold.php" method="post">
Name: <?php echo $customer_name ?> <input type="hidden" id="<?php echo $customer_name ?>" name="<?php echo $customer_name ?>">
<INPUT TYPE="image" src="images/arrow_back.png" id="arrow" alt="Back to Registration"> (Button to go back to Registration Page)
</form>
Thanks!
go-gold-summary.php should be changed like this.
<?php
$customer_name = $_POST['customer_name'];
?>
<form action="go-gold.php" method="post">
Name: <?php echo $customer_name ?> <input type="hidden" value="<?php echo $customer_name ?>" name="customer_name">
<INPUT TYPE="submit" src="images/arrow_back.png" id="arrow" alt="Back to Registration"> (Button to go back to Registration Page)
</form>
notice how I've changed this line
<input type="hidden" id="<?php echo $customer_name ?>" name="<?php echo $customer_name ?>">
into this
<input type="hidden" value="<?php echo $customer_name ?>" name="customer_name">
$_POST is an associative array and as you submit the form it will be populated like this:
$_POST["index"] = value;
where "index" is the text field "name" and value is the text field value.
You've missed that one in your code. Just update it with my code and it will work
Why you would not want to use the php session? Please give any reason for not to use it. I am asking this way since my reputation does not allow me to comment questions or answers any other than my own. Plese do not -1 for this.
Another way could be using cookies to store the data temporarily, but that and posting the data back and forth in the post request is really insecure compared to session.
there are very few ways to maintain variables across pages. The alternative is to have separate form on the second page with hidden text fields containing the $_POST data, and the submit button calls the previous page. No way of getting around the "back button" on a browser though unfortunately.
I missed the bold text about the session variables - disregard if this does not apply:
one way to maintain variables across pages on the server side is to use $_SESSION
first include the following at the top of your PHP pages to keep a session active:
session_start();
once you submit the for and move to page 2, add the following:
$_SESSION['customer_name'] = $_POST['customer_name'];
As well, on the first page, you could change the form element as such:
<input type="text" name="customer_name" value="<?PHP if isset($_SESSION['customer_name'] || !empty($_SESSION['customer_name'])) { echo $_SESSION['customer_name']; } ?>">
this will keep the filled in data and display it when the user returns tot he page, and if they put in something different it will be updated when they hit page 2 again.
This is just a project for my own learning purposes. For my project, users will be able to create polls and answer them. Each survey will have its own unique ID and can be accessed by its unique URL.
My problem is this. I know I can get around doing it this way, but this is a learning experience. When the user submits this form:
<form name="createPoll" action="polls.php" method="post">
Poll Title: <input name="pollTitle" type="text" /><br />
Option 1: <input name="pollOption" type="text" /><br />
Option 2: <input name="pollOption" type="text" /><br />
<input type="submit" value ="Submit Poll" /><br />
</form>
I want to run a script that will add this to my MySQL database and use the pollID that this script will generate for the URL like this:
http://www.mydomainname.com/polls.php?pollID=12345
where "12345" is the unique ID of the poll. My question is this:
What is the best way to bring the user to http://www.mydomainname.com/polls.php?pollID=12345 (assuming that the generated pollID will be '12345') on the submission of my form? Do I have to set the header in php in order to redirect them once the script has created the unique pollID?
Thanks
By the way: There is two inputs named "pollOption", be carefull :)
Your INSERT codes may be like that
$id=rand(100000,9999999999999999);
$checkid=mysql_query("SELECT ID FROM ID WHERE ID='$id'");
$checkidx=mysql_fetch_array($checkid);
if($_POST and $checkidx==null){
$title=$_POST['pollTitle'];
$opt1=$_POST['pollOption1'];
$opt2=$_POST['pollOption2'];
$insert=mysql_query("INSERT INTO ID,title,option1,option2 VALUES ('$id','$title','$opt1','$opt2')");
echo "Added! You re redirecting";
?>
<meta http-equiv="refresh" content="2;URL=http://www.mydomainname.com/polls.php?pollID=<?echo $id; ?>">
<?
}
And your polls.php may be like that;
$id=$_GET['id'];
if($id!=null){
$idget=mysql_query("SELECT * FROM blabla WHERE ID='$id'");
$idgetx=mysql_fetch_array($idget);
echo $idgetx[0] . $idgetx[1];
}
Generate the url, then use header() to redirect the page.
e.g.:
$id = 12345;
$url = 'http://www.mydomainname.com/polls.php?pollID=' . $id;
header('Location: ' . $url);
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />