I'm using php and I'm trying to add a functionality to my contact form that sends me the page that precedes the contact page.
I added this line of code on my form code:
$httpReferer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
$e_body = "Provenance : $httpReferer ";
This works fine and shows me a link, but the problem is that the link is the same contact page (http://...contact.php).
What I need is the page that the user visited just before getting to that contact.php page.
Anyone knows why is this happening?
Is there a way to go back 2 pages instead of one?
Thanks :)
One way to have a back button, is to add a hidden input to your form (seeing that is what you are using in a contact page), and using $_SERVER['REQUEST_URI'] as a value and assigning a session array to it and using sessions. Cookies could also be used, but I've used sessions in my example.
First start the session:
<?php
session_start();
// you can uncomment it to destroy previously set sessions
// session_destroy();
$_SESSION['back'] = $_SERVER['REQUEST_URI'];
?>
<form action="page2.php" method="post">
<input type="hidden" name="goback" value="<?php echo $_SERVER['REQUEST_URI'] ?>">
...
</form>
Then on the second page: page2.php
<?php
session_start();
// Your POST information for your contact code goes here
echo "Go back";
?>
Or, to have the full http call:
$link = "http://" . $_SERVER['SERVER_NAME'].$_SESSION['back'];
echo "Go back";
Sidenote: As I stated in comments,
The only way I know to go back 2 pages is with javascript:window.history.go(-2) which you could implement that in PHP with an echo.
Another way would be to use a breadcrumb method, but that would require some fancy work.
$_SERVER['HTTP_REFERER'] isn't fully reliable.
Read: https://stackoverflow.com/a/6023980/ as to why.
You could also use a header to redirect, but make sure you're not outputting before header.
Ref:
http://php.net/manual/en/function.header.php
How to fix "Headers already sent" error in PHP
References:
http://php.net/manual/en/features.sessions.php
http://php.net/manual/en/reserved.variables.server.php
Footnotes:
What I need is the page that the user visited just before getting to that contact.php page.
If there wasn't a referer to the page, then there is no way for a user to go back, because there is nothing to go back to, unless they use their browser's back arrow button.
A referer is a link that a person would have clicked from, either from your site or another.
If there was no referer, you can use javascript:window.history.go(-1).
If you really want to use $_SERVER['HTTP_REFERER'] (see other comments), then store this in a session when the contact form is loaded so you can use this when the form is submitted.
// Store the referring URL when loading the contact form.
$_SESSION['ref'] = $_SERVER['HTTP_REFERER']
// Redirect user back to referring URL when submitting the form.
header('Location: ' . $_SESSION['ref']);
unset($_SESSION['ref']);
die;
Hope this helps.
header('Location: '.$_SERVER['HTTP_REFERER']);
die;
Hope it will help you
Related
OK so my goal is to get this page:
http://www.orchidfilmcompany.co.uk/Payment.aspx
to work in my php wordpress page.
I dont really know where to start, my whole site is ready to go except for this new pay online page.
The guy who created the .NET page has provided me with the Response.Redirect code which has the merchant peoples url with instID etc. The user will be redirected to this url to complet the payment
I have been looking around online and I found the the equivelant code in php for this is:
Header("Location: $url");
My problem is I dont know what to do with that?
Thats all I need is input box where the user can enter the amount they want to pay, they press submit and it redirects them to the url that I have in the Response.Redirect code. Uses the amount that they entered in the box and they can complete the payment.
If anyone could assist I would really appreciate.
Thanks in advance.
header() function is used to redirect the browser to a specific location.
If you already have the URL where you should redirect the client and you need just to add some amount that came from an input .. you should append that amount in the redirect url
eg:
purchase.html - include this form on your page
<form method="post action="/redirect.php">
<input type="text" name="amount" value="" />
<input type="submit" name="sumbit" value="Purchase" />
</form>
redirect.php - put this file next to your html file
<?php
$amount = (int) $_POST['amount'];
$urlToRedirect = 'https://secure.wp3.rbsworldpay.com/wcc/purchase?instId=XXX&cartId=OFMaterial¤cy=GBP&amount='.$amount;
header('Location: '.$urlToRedirect);
exit;
?>
The form should have an action assigned to it, which is the page that will parse the form.
On that page (or within your parsing bit of the code), make sure that the redirect happens there.
The header statement is correct, e.g.:
<?php
header('Location: http://www.example.com/');
exit;
?>
Would redirect to example.com. So, construct the URL you want to redirect to there.
Please note: header directly modifies the headers returned by your webserver and therefore it cannot be called if you already sent other (HTML) output to your browser. Also see the documentation on header here: http://php.net/manual/en/function.header.php
You could try having a form which submits to a PHP page
The PHP page could then pick up the form variables using $_POST['FORM_VAR']
Build a $url variable from the submitted variables + .net page url
Finally use the header("Location: $url"); to take in the built url and redirect.
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?>
How to check if the user has entered the page by clicking on the button and not from copy pasting the URL ?
For example, if a user has clicked on Register I want him/her to go to that page only by clicking the Register button and not by copy pasting the link.
Also, is it a good practice to give the page name on the address bar or should I have to hide the page. If I am hiding the page will I be able to do that ?
For example, if localhost/projname/register.php. I don't want people to see the register or login or about or anything on the address bar except localhost/projname.
Maybe check if he used $_POST, something like:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
// do ya thing
}
else
{
?>
<form action="index.php" method="post">
are you sure? <input type="submit" value="yes">
</form>
<?php
}
?>
You can use the HTTP_REFERER data of the $_SERVER reserved variable to see where did the user come from.
if(empty($_SERVER['HTTP_REFERER'])) {
// if we are here, the user copy pasted the url.
}
As for your second question, you can't totally "hide the page" like you're suggesting. The web server must know which page to show, so the browser must know has well.
You can however obfuscate the page name. For example you can call the page "sfhjgdjkfg" so the user won't be able to know that this is the "registering" page. But I think it's really a bad idea, why in the first place want you to hide this ?
One method is to use $_SERVER['HTTP_REFERER'] to verify that they clicked a link from your site, but this method isn't fool-proof as many Firewall and Anti-virus suites will remove the Referrer information.
A better method would be to generate a temporary session token on the pages of your site, and check for that token when the Register page is opened.
If your form uses POST parameters, the browser will pass on some POST data. You could then check
if (empty($_POST)) {
//didn't click the button, just went straight to the url
}else{
//did click the button
}
I have a one page site that has PHP code in it. Once the user presses 'Send', this sends the information to my email, then displays a messagebox saying that the action was a success to the user - great.
After the messagebox is closed, the website stays at website.com/report.php. Is there a way to redirect it back to the original page.
Also, any way to change the icon in the messagebox that pops up? Here is the code that I have:
<script language="JavaScript">alert("Your request has been sent. I will contact you soon!");</script>
Thanks.
Look into window.open and window.location
Place it after your alert()
http://www.tizag.com/javascriptT/javascriptredirect.php
Also, to answer your messagebox icon question: No, it is browser-dependent and not modifiable.
If you want to do that, your are going to need to fake it with html/css and javascript.
<script language="JavaScript">
alert("Your request has been sent. I will contact you soon!");
window.location.assign("http://website.com");
</script>
If you want to change the icon in alert box or make it look a little fancy, you could try YUI dialog
Use this code to display the alert:
function displayAlert(message, redirect) {
alert(message);
window.location.href = redirect;
}
Then, you can use code like:
displayAlert("This is the message", "http://redirect.the/user/here");
Use the php header command
<?php
header("Location: http://www.example.com/");
exit;
?>
To do a redirect in PHP, use header("Location: page.php"); for this. Before and after this your code shouldn't be sending any other output to the response. Eventually use exit(); to terminate the script afterwards.
If you need the page which was requested right before this page, then best what you can do is to include its URL as request parameter of the link to report.php and use it as redirect destination. E.g.
report
and in the report.php pass it as hidden input field:
<input type="hidden" name="referrer" value="<?php echo getParam("referrer"); ?>">
And after submitting the report do:
header("Location: " . getParam("referrer") . ")"; // getParam() returns sanitized GET parameter.
An alternative is to use the $_SERVER['HTTP_REFERER'] header (yes, including the typo) for this, but this is just not that reliable as it may be disabled or spoofed by the client.
I believe a more elegant solution is to simply present the user with a confirmation page (instead of an alert box), and place a link to the previous page there.
That would at lease work for all users.
For those users with javascript a little Ajax (jQuery) could submit the form for you, and display the confirmation nessage. All without leaving the page the user is on (negating the need for any fancy redirects).
Towards the end of your php, use this:
header('location: home.php');
This will cause the browser to load the original page.
I don't believe that the standard alert box can be altered, aside from the message. You can't change the title or the buttons, either.
Frank
I have the following code on my site (using php and smarty) to try and avoid a form resubmitting when I hit f5:
if ($this->bln_added == false) {
if (isset($_POST['submit'])) {
$this->obj_site->obj_smarty->assign('title', $_POST['tas_heading']);
$this->obj_site->obj_smarty->assign('desc', $_POST['tas_description']);
}
} else {
$this->obj_site->obj_smarty->assign('title', '');
$this->obj_site->obj_smarty->assign('desc', '');
unset($_POST);
}
bln_added is false by default, but changes to true once the form is successfully submitted. The smarty variables title and desc are used in the template to keep the form content there in case there is a user error and they need to change what they entered.
If the form is submitted successfully it sets bln_added = true, so the second bit of code should not only clear the form fields, but also empty $_POST. But if I press f5 the post data is still there.
Any ideas?
Your method could work in theory, but there's a much easier way.
After submitting the form successfully, perform a redirect. It doesn't matter where to, but it'll clear the $_POST.
header('Location: http://www.example.com/form.php');
In your case, it sounds like you want to redirect to the page you're already on. Append a $_GET parameter to the URL if you want to display a confirmation message.
Hope this helps,
Tom
The solution is a pattern commonly known as Post/Redirect/Get
The best way to handle forms is to use self-submission and a redirect. Something like this:
if (isset($_POST)) {
// Perform your validation and whatever it is you wanted to do
// Perform your redirect
}
// If we get here they didn't submit the form - display it to them.
Using the CodeIgniter framework:
function index() {
$this->load->library('validation');
// Your validation rules
if ($this->form_validation->run()) {
// Perform your database changes via your model
redirect('');
return;
}
// The form didn't validate (or the user hasn't submitted)
$this->load->view('yourview');
}
You can rewrite your form-submit into AJAX-way. If you need to show HTML-content, return it in JSON-format and insert with JavaScript(jQuery for example.)
I solved this (in php) by:
in the form add a unique identifier (id+counter) not based on time() (!!!)
post to a separate file (postform.php) that checked for a session with that unique identifier
a) if session with unique identifier was NOT found: post to the database and fill session with unique identifier
b) if session with unique identifier was found: do nothing
after either 3a/3b redirect to result page with header('Location: http://mydomain.com/mypage')
Result is:
no resubmit actions on either refresh/backbutton and only resubmit warning on double click backbutton (but no resubmit action)
Use Header location after successful post action
header('Location: '.$_SERVER['HTTP_REFERER']);
It works for me if I use either header() or exit() at the end of my code, for example, after I save some data.
The best method I found is using javascript and css. Common php redirection method header('Location: http://www.yourdomain.com/url); will work but It cause warning " Warning: Cannot modify header information - headers already sent" in different frameworks and cms like wordpress, drupal etc. So my suggestion is to follow the below code
echo '<style>body{display:none;}</style>';
echo '<script>window.location.href = "http://www.siteurl.com/mysuccesspage";</script>';
exit;
The style tag is important otherwise the user may feel like page loaded twice. If we use style tag with body display none and then refresh the page , then the user experience will be like same as php header('Location: ....);
I hope this will help :)
the answer you are looking for is this magic one liner:
header('Location: '.$_SERVER['HTTP_REFERER']);
e.g
if(isset['submit']){
//insert database
header('Location: '.$_SERVER['HTTP_REFERER']);
}
Header redirect after post is necessary, but insufficient.
In PHP side after submitting the form successfully, perform a redirect. Eg. header('Location: http://www.example.com/form.php');
But it is not enough. Some users press links twice (doubleclick). A JavaScript is required that would disable submit button after first click.
Try my own one, maybe it isn't best solution (done quickly), but I've test it and it works. Tested on Chrome. Click to see how it looks BR
<?php
session_start(); // Start session
?>
<html>
<head>
<title>
Test
</title>
</head>
<body>
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
<?php
if(isset($_POST['submit']))
{
$_SESSION['name'] = $_POST['name']; // Assign $_POST value to $_SESSION variable
header('Location: refresh.php'); // Address of this - reloaded page - in this case similar to PHP_SELF
} else session_destroy(); // kill session, depends on what you want to do / maybe unset() function will be enough
if(isset($_SESSION['name']))
{
$name = $_SESSION['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
</body>
</html>