I have a form that is supposed to store some of its data into a session. For the purpose of this example.
This information is then collected on another page.
<?php
session_start();
print_r($_SESSION['booking-form']); ########### for debugging purposes ###########
if ($_SESSION['booking-form']) {
echo $_POST['GT_title']
?>
<!DOCTYPE html>
<html>
<?php
}
elseif ($_SESSION['booking-form']) {
}?>
</html>
Now although the debug is working the echo is not working ie. echo S_POST['GT_title'].
How do I echo the information on the second page.
Can I echo it wherever I want it in the html (ie. in the middle of the body somewhere with
On the first page some data in the form can be changed with options. This would need to update the session before the page is changed.
CLARIFICATION
For the purpose of a booking form. The user filled in a series of options that were then echo'd on the next page. At this point they need to log in so the form data must enter into a session. The session data should then be returned on a third page.
1) what information? $_POST['GT_title'] would refer to a form element, presumably on the previous page. Does it exist? Is it filled in? what are you expecting?
2) You can echo where ever you like.
3) clarify? you can update a session with post values easily.
$_SESSION['foo'] = $_POST['bar']
your question isn't really that clear.
You can echo it wherever you want but if it doesn't exist or doesn't have a value then it might appear to be not working. To know for sure use var_dump($_POST['GT_title']);
For your echo question: Are you sure that GT_title is set? Posting the form on your previous page might help.
You can echo wherever you want, you can just put
<?=$varname?>
anywhere in your html.
You can also update your session wherever you want.
$_SESSION['abc'] = value;
echo '<pre>';
print_r($_POST);
echo '</pre>';
Print it after your header.
I hope this helps a little :)
Related
I want to show different div with different contents in different condition.
If customer is logged in, then show content A,
If customer is not logged in, then show content B,
This is the script I have, not sure it is correct or not.
<?php if (!$logged) {
$disp_div=1;
} else {
$disp_div=0;
} ?>
This is the jQuery
<script type="text/javascript" >
$(document).ready(function(){
var show=<?php echo $disp_div; ?>
if(show==1)
{
$('#div_logged_in').show();
$('#div_not_logged_in').hide();
}
else if(show==0)
{
$('#div_logged_in').hide();
$('#div_not_logged_in').show();
}
});
This is the HTML
<div id="div_logged_in">
Content A
</div>
<div id="div_not_logged_in">
Content B
</div>
A: Why !$logged is wrong:
You use a local variable. Next time your user refreshes the page he won't be logged in anymore. For that you can store variables in a array called $_SESSION . This array is saved for a client session on you webserver. As longs as the user stays there it will always remain the same (until YOU change it). For that you need a session_start(); in the first line of you main PHP script.
B: Why the javascript part is a security leak:
Your website is designed not to filter the content that is sended to the user. Every user gets the whole content, just the visibility is changed. In this way every advanced user can just look into your code and see all the secrets you want to hide.
C: What is the right way?
It just some PHP that echos HTML without Javascript and uses $_SESSION:
<?php
if($_SESSION["loggedIn"] == "yes") { //You have to set that somewhere else just like $logged
?>
<p> You ARE logged in. </p>
<?php } else { ?>
<p> You ARE NOT logged in. </p>
<?php
}
?>
I don't know what is $logged. If it is the variable to find whether the user is logged in, then your condition is just opposite of your requirement. You are showing div_logged_in when the user is not logged in from this condition.
if(show==1)
{
$('#div_logged_in').show();
$('#div_not_logged_in').hide();
}
The value of show will be 1 when $logged is false. So change the condition and you will get it. In this scenario, i would suggest you to go with SESSIONS. You can use anywhere to check whether the user is logged in or not.
First off, you need to start reading about sessions and the $_SESSION superglobal.
After that, throw that script away, and look for a proper tutorial, I found a very nice one here: http://net.tutsplus.com/tutorials/php/a-better-login-system/ - though it may be a bit advanced since it talks about ACL, which you probably won't need.
But if you can try and understand the rest of the tutorial, you should be fine. Good luck!
Please do not depend on client-side validation because its a security flow within your application, what if the customer viewed the source code for your page? then they see hidden contents.
Your approach is correct but you have to use $_SESSION or $_COOKIE not if (!$logged) and as I said, do not out put the content totally.
use
if($_SESSION["username"])
you can set it in the login.php file
and destroy it by using session_destroy() on the logout.php
I've written a bit of code to upload a file to a server. When the file is successful I made my code go to another web page. On this web page I want to print the file properties which were gained from the previous page so I am using Sessions in PHP.
//Starts up a new PHP session
session_start();
$_SESSION['file']=$_FILES["file"];
$_SESSION['name']=$_FILES['name'];
$_SESSION['type']=$_FILES['type'];
$_SESSION['size']=$_FILES['size'];
$_SESSION['tmp_name']=$_FILES['tmp_name'];
That is my session on page1. Then, when the file is successful, I send the user to page2.
header( 'Location: page2' ) ;
Now, on page2, I have this right at the top of my .php page:
<?php
//Starting session
session_start();
?>
Then, further down for me to be able to print each variable out I've got:
<?php
Print_r ($_SESSION['file']);
?>
I get all my information all jumbled into a long sentence when this is done. I want to have control over the information and print it nice and neatly. What am I doing wrong? I've researched into loads of different ways of doing this and nothing has helped so far.
Tried that, also tried just printing SESSION, also tried echoing each one seperately with the words [Array] being printed only.
Thanks in advance!
Use two dimensional array like below
$_SESSION['upload1']['file']=$_FILES["file"];
$_SESSION['upload1']['name']=$_FILES['name'];
$_SESSION['upload1']['type']=$_FILES['type'];
$_SESSION['upload1']['size']=$_FILES['size'];
$_SESSION['upload1']['tmp_name']=$_FILES['tmp_name'];
on file2.php
<?php
print "<pre>";
print_r($_SESSION['upload1']);
print "</pre>";
?>
You are dealing with white-space breaks vs HTML breaks.
Just print it as <pre> and you're good to go.
<pre>
<?= print_r ($_SESSION['file']); ?>
</pre>
print_r() will print out your information in a nice ASCII-Art like format. The HTML engines render this unreadably. Chose "view source" (Ctl-U) in your browser to view it in a human-understandable form.
You can also install Xdebug which will make really nice formatting : http://xdebug.org/docs/install
and see: https://stackoverflow.com/search?q=how+to+install+xdebug if you have any issues installing xdebug
Use a table to display the data (or am i missing something !?!) :
<table>
<tr><td>File Name</td><td><?php echo $_SESSION['name'] ?></td></tr>
<tr><td>File Size</td><td><?php echo $_SESSION['size'] ?></td></tr>
</table>
add whatever extra info you need ...
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 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
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>