I have a form where the user will input a bunch of data. It is set up like this:
<form action="add.php" method="post">
This makes it so that when I click my submit button it will go to the add.php page. add.php however is a blank page because it only runs some SQL queries and does nothing else.
I want it so that when I click submit, the information is sent one place and the screen goes to another. My button is set up like this:
<input type="submit" value="Submit">
Just to make sure I am explaining the issue correctly, when I click submit I want the data from the form to go to add.php, and the browser to display a different page rather than displaying the add.php page, which is what it is doing right now.
The solution is easy, send data to add.php, in the end of your process. redirect to another page, let's say page.php
on your add.php
<?php
/// do you mysql stuffs here
header('Location: page.php');
?>
Here is two solutions :
Asynchronous solution
Use Javascript and ajax to send the data to add.php asynchronously and redirect the user to the page you want.
This solution might be not a good one, because the process result of add.php is ignored (if you redirect the user before getting the result)
Synchronous solution
Redirect the user to add.php, then, redirect the user to the page you want at the end of the process.
After your SQL Queries are done on add.php you can use the header function and pass your data via get-method:
header("Location: nextSite.php?key=value"); //Replace key and value with whatever you want
we can use a session or cookie in PHP.
Session:
//On page 1
$_SESSION['name'] = $formvariable; // You can use document.getElementById('form input
name')
//On page 2
$var_value = $_SESSION['name'];
Using include method
//On page 1
This page has a form without submit button
//On page 2
This page has a submit button
so we include page 1 something like this.
EX:
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
I hope this will help you to solve your issue- thanks!
When I press the 'refresh' button on my browser, it seems that $_POST variable is preserved across the refresh.
If I want to delete the contents of $_POST what should I do? Using unset for the fields of $_POST did not help.
Help? Thanks!
The request header contains some POST data. No matter what you do, when you reload the page, the rquest would be sent again.
The simple solution is to redirect to a new (if not the same) page. This pattern is very common in web applications, and is called Post/Redirect/Get. It's typical for all forms to do a POST, then if successful, you should do a redirect.
Try as much as possible to always separate (in different files) your view script (html mostly) from your controller script (business logic and stuff). In this way, you would always post data to a seperate controller script and then redirect back to a view script which when rendered, will contain no POST data in the request header.
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// This code can be used anywhere you redirect your user to using the header("Location: ...")
if (array_key_exists('postdata', $_SESSION)) {
// Handle your submitted form here using the $_SESSION['postdata'] instead of $_POST
// After using the postdata, don't forget to unset/clear it
unset($_SESSION['postdata']);
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.
Use case/example
<!-- Demo after submitting -->
<?php if (array_key_exists('postdata', $_SESSION)): ?>
The name you entered was <?= $_SESSION['postdata']['name']; ?>.
<!-- As specified above, clear the postdata from the session -->
<?php unset($_SESSION['postdata']); ?>
<?php endif; ?>
<!-- Demo form -->
<?php if (!isset($_SESSION['postdata'])): ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name" /><br />
<input type="submit" value="Submit" />
</form>
<?php endif; ?>
Simple PHP solution to this:
if (isset($_POST['aaa'])){
echo '
<script type="text/javascript">
location.reload();
</script>';
}
As the page is reloaded it will update on screen the new data and clear the $_POST
;)
this is a common question here.
Here's a link to a similar question. You can see my answer there.
Why POST['submit'] is set when I reload?
The basic answer is to look into post/redirect/get, but since it is easier to see by example, just check the link above.
My usual technique for this is:
<?php
if ($_POST) {
$errors = validate_post($_POST);
if ($!errors) {
take_action($_POST);
// This is it (you may want to pass some additional parameters to generate visual feedback later):
header('Location: ?');
exit;
}
}
?>
How about using $_POST = array(), which nullifies the data. The browser will still ask to reload, but there will be no data in the $_POST superglobal.
$_POST should only get populated on POST requests. The browser usually sends GET requests. If you reached a page via POST it usually asks you if it should resend the POST data when you hit refresh. What it does is simply that - sending the POST data again. To PHP that looks like a different request although it semantically contains the same data.
This will remove the annoying confirm submission on refresh, the code is self-explanatory:
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER[REQUEST_URI]);
exit;
}
if (#$_SESSION['postdata']){
$_POST=$_SESSION['postdata'];
unset($_SESSION['postdata']);
}
You can't, this is treated by the browser, not by any programming language. You can use AJAX to make the request or redirect the user to the same (or another) page.
The "best" way to do this is Post / Redirect / Get
http://en.wikipedia.org/wiki/Post/Redirect/Get
After the post send a 302 header pointing to the success page
I had this problem in an online fabric store, where there was a button to order a fabric sample on the product page, if a customer had first ordered a product and then wanted to order a sample of a different colour their previous order would be duplicated, since they never left the page and the POST data was still present.
The only way I could do this reliably was to add a redirecting page (or in my case in WordPress, add action to "parse_request" for a mock url), that redirects back to the referring page.
Javascript:
window.location.href = '/hard-reset-form';
PHP:
header('Location: ' . $_SERVER['HTTP_REFERER']);
die();
This way you are coming back to a new page, all POST data cleared.
Set an intermediate page where you change $_POST variables into $_SESSION. In your actual page, unset them after usage.
You may pass also the initial page URL to set the browser back button.
I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,
then on the actual $_post's
I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.
After it does whatever to the data, I run a function to clear all the $_post data for each section.
you can hit refresh till your blue in the face it won't do anything but refresh the page and display.
So you just need to think logically and make it idiot proof for your users...
try
unset($_POST);
unset($_REQUEST);
header('Location: ...');
it worked for me
I can see this is an old thread, just thought I'd give my 2cents. Not sure if it would fit every scenario, but this is the method I've been successfully using for a number of years:
session_start();
if($_POST == $_SESSION['oldPOST']) $_POST = array(); else $_SESSION['oldPOST'] = $_POST;
Doesn't really delete POST-ed values from the browser, but as far as your php script below these lines is concerned, there is no more POST variables.
This is the most simple way you can do it since you can't clear $_POST data by refreshing the page but by leaving the page and coming back to it again.
This will be on the page you would want to clear $_POST data.
<a class="btn" href="clear_reload.php"> Clear</a> // button to 'clear' data
Now create clear_reload.php.
clear_reload.php:
<?php
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
The "clear" button will direct you to this clear_reload.php page, which will redirect you back to the same page you were at.
If somehow, the problem has to do with multiple insertions to your database "on refresh". Check my answer here Unset post variables after form submission. It should help.
The Post data can be clear with some tricks.
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST); //unsetting $_POST Array
header("Location: ".$_SERVER['REQUEST_URI']);//This will let your uri parameters to still exist
exit;
}
?>
In my case I have used the below trick to redirect user to the same page once the $_POST operation has been done.
Example:
if(!empty($_POST['message'])) {
// do your operation here
header('Location: '.$_SERVER['PHP_SELF']);
}
It is a very simple trick where we are reloading the page without post variable.
I see this have been answered. However, I ran into the same issue and fixed it by adding the following to the header of the php script.
header("Pragma: no-cache");
Post/Redirect/Get is a good practice no doubt. But even without that, the above should fix the issue.
I had a form on my account page which sent data with POST method and I had to store the received data in a database. The data from the database was supposed to be displayed on the webpage but I had to refresh the page after the POST request to display the contents in database. To solve this issue I wrote the following code on account page:
if (isset($_POST['variable'])){
echo '
<script type="text/javascript">
location.href="./index.php?result=success";
</script>';
}
Then on index.php I refreshed the page and sent the user back to my account page as follows:
if (isset($_GET['result'])) {
echo'<script>
//reloads the page
location.reload();
//send user back to account.php
location.href="./account.php"
</script>'
}
You should add the no cache directive to your header:
<?php
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
?>
This works for me:
<?if(isset($_POST['oldPost'])):?>
<form method="post" id="resetPost"></form>
<script>$("#resetPost").submit()</script>
<?endif?>
I need to make sure users don't go to the download page unless they fill out the form on the register page. I need help inserting a session variable into the submission script, something like
$_POST['authenticated'] = 'yes';
Then on the download page require this:
<?php
session_start();
if($_SESSION['authenticated'] !== 'yes') {
header("Location: http://domain.com/default.php");
};
?>
I need to make them successfully fill out the form - then add it to the session - then once on the page - purge the session info but don't know how
I need a push in the right direction on how to require the form to be filled out in order to get to download page.
EDIT
on purchase-registration.php (form) I added this
$authReq=$_SESSION['authReq']=rand(1,65535);
and in the form(s) on that page I added this
<input type='hidden' name='authreq' value='<?PHP=$authReq?>'>
In the processor script (form submit) I added this:
"$authReq = $_POST["authReq"];"
and on the final page, the download-software.php which Im trying to restrict access to I added this
<?php
session_start();
if($_SESSION['authReq']==$_POST['authReq']) {
header("Location: http://kinetick.com/V3/download-free.php");
};
?>
no joy, is this incorrect?
thx
The way I usually handle that is:
on the page that renders the form:
$authReq=$_SESSION['authReq']=rand(1,65535);
on the form:
<input type='hidden' name='authreq' value='<?PHP=$authReq?>'>
and on the submitted page
if($_SESSION['authReq']==$_POST['authReq'])....
I Have a php form page where users fill the data and process page to add data to database, Its working fine, But problem is I need the results from process page to be displayed back on to my main page? How to get results back to main page?
In the form's action attribute, set the path to $_SERVER['PHP_SELF'] rather than processing file. This way, form will submit to same page where you can process it.
<form action="<?php echo $_SERVER['PHP_SELF'];?>">
.....
</form>
How about
<form action="mainPage.php" ...>
Simple and your Data will be on the main page.
Use sessions. In script assign a error message to session variable and do redirect. On script.php
$_SESSION['error'] = 'Incorrect email';
index.php
echo $_SESSION['error'];
Don't forget session_start() in begin of scripts.
There's a wide variety of ways, depending on what you're talking about. You'll likely want to use session variables, though. In the processing script:
<?php
start_session();
// Do your processing here
$_SESSION['myvar'] = $finished_data;
?>
And in the main page that called it:
<?php
session_start();
if(!empty($_SESSION['myvar'])) {
$data = $_SESSION['myvar'];
}
// Use $data here as you need
?>
Looks to me like you need to include some Javascript here, then post the returned data to wherever you want. there is.. post to same pagewith...document.getElementById('yourDiv').innerHTML = 'yourReturnedData';
or with $_GET variables.
example...
yoursite.com/yourPage.php?data1=data1&data2=data2
Get returned data by ...
$var1 = $_GET['data1'];
$var2 = $_GET['data2'];
Hope this is of use
Thanks to Col. Shrapnel I am using a VERY basic PHP script to send emails. The form is located here.
This is the script:
<?php
mail('JBIRD1111#gmail.com','Live Date Submission',implode("\n\n",$_POST));
header("Location: thankyou.html");
?>
When a user submits the form, they are redirected to a thankyou.html page. I want to edit the code to display a javascript alert, instead of a redirect. I don't have much PHP knowledge, so how would I edit this code to return a alert instead of a redirect?
Actually, if you want to send a Javascript alert instead I would recommend using some basic jQuery work. I would also take a look at the AJAX section of the documentation.
Otherwise you can inset some javascript in the original form page.
session_start();
$_SESSION['message'] = "<script>alert('Thank you so very much! You rock!');</script>";
header("Location: originalformpage.html");
and on the original form page
session_start();
if(isset($_SESSION['message']))
{
echo($_SESSION['message']);
unset($_SESSION['message']);
}
Replace the header line with:
print("<script>alert('Thank you so very much! You rock!');</script>");
Not tested but should work.