PHP Losing session variables upon going back to previous page - php

The home page on my website has a form with two fields: Make of the Car (carmake) and Car Model (carmodel). Upon submit, it takes the user to the 2nd page that displays information about the specific make and model that the user has input on the homepage.
I am using post-method to pass the variables to the 2nd page, where I start a new session with the two variables:
<?php
session_start();
$_SESSION['carmake']=$_POST['carmake'];
$_SESSION['carmodel']=$_POST['carmodel'];
?>
This works fine. On this 2nd page, I have a link for a 3rd page that uses the same two session variables. So on the 3rd page, I start the page with the session function and the session variables are available for use. No problem so far.
There are 2 problems I am experiencing from this point onwards:
Problem 1: I have a button on the 3rd page that links back to the 2nd page. When I use this button to go back to the 2rd page, the 2nd page does not echo the session variables. However, if I use the browser 'back' button to go back to the 2nd page, I am asked to "confirm resubmission" which I do and then 2nd page correctly echoes the session variables.
My question 1: How can I design the navigation to previously visited pages without losing the session variables?
Question 2: Is there a way to avoid having to "confirm resubmission" (when using the browser back button) on a previously visited page that uses session variables?
(I am a newbie here and apologize in advance for the long post for what may be a very simple question.)

Question 1 solution:
Change your code
<?php
session_start();
$_SESSION['carmake']=$_POST['carmake'];
$_SESSION['carmodel']=$_POST['carmodel'];
To
<?php
session_start();
if(isset($_POST['carmake']))
$_SESSION['carmake']=$_POST['carmake'];
if(isset($_POST['carmodel']))
$_SESSION['carmodel']=$_POST['carmodel'];
It will set session value only if form is submit (which is submit from Form1), so when you click back button, it will not set blank values and will keep last session value remains)
Question 2 solution:
<?php
session_start();
if(isset($_POST['carmake']))
$_SESSION['carmake']=$_POST['carmake'];
if(isset($_POST['carmodel']))
$_SESSION['carmodel']=$_POST['carmodel'];
if(isset($_POST['carmake']) || isset($_POST['carmodel'])){
# Redirect on same page when submitting the form
# will not ask for form submission when click back on browser page
header("Location: page2.php")
exit;
}

Problem 1: Unless you are checking to see if $_POST has values before you assign them, the sessions will get empty values. Turn on a higher error log level and display errors and you should see a notice about an undefined variable. Also, it works when you confirm submission because you are re-POSTing the data to the second page.
Question 1: Check that the POST variables are not empty() before assigning them.
Question 2: Not that I am aware of, you are going back to a page that your browser previously POSTed to and it wants to know if you want to again (to get the "same" results as before)
UPDATE: Also, you should post more code.

I know I am late here, but just thought to share my solution. I hope this helps someone.
Question 1 : Solution
Store the value in session only if form is submitted.
<?php
session_start();
if(isset($_POST['carmake'])) $_SESSION['carmake'] = $_POST['carmake'];
if(isset($_POST['carmodel'])) $_SESSION['carmodel'] = $_POST['carmodel'];
/* Rest of the code goes here */
Question 2 : Solution (easy alternative)
Cache control and Session cache limiter prevents form resubmission when using browser back button.
<?php
session_start();
header("Cache-Control: no cache");
session_cache_limiter("private_no_expire");
/* Rest of the code goes here */
~ Full code ~
<?php
session_start();
header("Cache-Control: no cache");
session_cache_limiter("private_no_expire");
if(isset($_POST['carmake'])) $_SESSION['carmake']=$_POST['carmake'];
if(isset($_POST['carmodel'])) $_SESSION['carmodel']=$_POST['carmodel'];
/* Rest of the code goes here */

Related

Storing Session information and linking to new page on click

I hope this isn't stupidly simple. I am completely new to web dev.
I have list items that I styled as buttons.
I want to be able to link to a new page as well as store some information when the list items are clicked. I want to be able to store which list item was clicked in a Session variable.
How do I accomplish this/ is there a better way to accomplish the same thing?
Sessions Step By Step
1- Defining session before everything, Ideally do it on very top of the document so no output is being exposed etc like this
<?php
session_start();
?>
2 - Set your session inside a page and then you have access in that page. For example this is page 1.php
<?php
//This is page 1 and then we will use session that defined from this page:
session_start();
$_SESSION['danish']='danish';
?>
3- Using and Getting session in 2.php
<?php
//In this page I am going to use session:
session_start();
if($_SESSION['name']){
echo 'Your name variable Is Here! :) ';
}
?>
In short its like you assign session variable in a page and then using same declarative syntax instead of assigning you call the variable and PHP do the magic to check if that session variable was created and hold the value so, in short i can write my code like this
First Page
<?php
session_start();
$_SESSION['myvar']='myvalue';
?>
Second page
<?php
session_start();
echo $_SESSION['myvar'];
?>

How can I transfer a value from a page to another?without changing pages

I'm trying to build a website with only 2 pages.
Page 1
In this page theres a buttom and everytime the buttom is clicked it increases the value of the label on page 2.
Page 2
In this page there is only one label a value that is increased by page one
Could someone give me an example
consider the following link as a solution to your problem using AJAX and jQuery.
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
Go through sessions
In your page one
<?php
session_start();
$_SESSION['myValue']=10; // here your value.
?>
In page two
<?php
session_start();
echo $_SESSION['myValue'];
?>
Another way
<a href='pageone.php?myValue=12'>click</a>
then in any other page, you can access
$_GET['myValue'];
Depending on what resources you have available, you could use AJAX to save the value to the database/XML file on PAGE 1. Then write a script to retrieve the value on PAGE 2.
Alternatively, you could look into saving a SESSION variable on PAGE 1 and retrieve that on PAGE 2.
Session Links:
PHP SESSION Tutorial
PHP Manual - SESSIONS
Js for the button page
var counter=0;
function buttonclick(){
counter++;
window.postMessage(counter);
}
Js for display:
window.onload=function(){
window.addEventlistener("message", handle,false);
}
function handle(event){
alert(event.data);
}
This uses the browsers internal messaging system to transfer the value from one window to another. If you want to transfer it even if page2 is not opened use AJAX to send it to the server and use SESSIONS to store it.

Page refresh causes form submission [duplicate]

This question already has answers here:
Avoid resending forms on php pages
(6 answers)
Closed 9 years ago.
I have a webpage that contains a form that uses the POST method and references the same page it is on for submission. I am using a PHP include file that contains an if statement that runs when the submit value is set. For some reason though, after one submission, every time you refresh the page it submits the form with the previously submitted data (The browser warns of this before refreshing the page). What causes this, and what could I be doing wrong?
This is expected. You should have the form submit to a handler that has a unique URL, whether it be a query string or a different URI. One solution (of many) would be to change your form action:
<form action="?action=submit" method="post">
<input type="hidden" name="action" value="submit" />
...
and then in the PHP script handle the form, then change the context back to a URL without the hidden query string
if (!empty($_POST['action']) && $_POST['action'] == 'submit') {
// do stuff
header('Location: '.$_SERVER['SCRIPT_NAME']);
die();
}
Note the query string is not actually present in $_POST but we keep it there so browsers don't consider it to be a redirect loop.
i had the same issue with one of my pages.
the reason is that when the browser warns you that it will submit the form again, that means it is going yo be the same exact thing when you click on a submit button.
I did 2 things to avoid it but i am sure there many other ways.
1. Do not let the page echo the form again after succesfull submission of the form.
mine was like this
<?php
if(!isset($_POST['submit'])) {
include(form.php);// you can modify this according to your needs.
} else {
//display your message about what happened with the form.
}
?>
with that approach, your page will not the contaion a form to submit HOWEVER this will not prevent it from submitting on refresh.
2. if the form is submitted create a contoller input that carries a value indication that the form is already submitted. for example , place this into your form:
<?=(isset($_POST['submit']))?"" :"<input type-"hidden" name="submit_stat" value="true" />" ; ?>
and when you process your form when it is submitted check it with your php and make the script act on that variable like this:
<?php
if($_POST['submit_stat']==true) {
//do not process the form here.
//stop your script
}
?>
Another thing you can do is redirect your page to another page other than the page that handles the form. i believe this is the safest one.
Another Way to prevent this is to move the Post Data to Session, redirect, collect Post back from Session and delete Session Post Data.
if(!empty($_POST) && empty($_FILES)){
// move post to session
// redirect to same url (don't forget possible get query)
}else{
// collect post from session
// unset post from session
}
Build this as default and you should never have problems with post data.
Only exceptions are File uploads. In this case redirect *after* post processing manualy.

Pass url variable on to next page?

I need some help on passing a url php variable onto the next page. I've tried searching throughout the site for help and I've spent a lot of time trying to figure this out with no luck. Basically I need to be able to change the paypal link button id on page 2 with the url variable from page 1.
The variable is initially passed along with the URL: http://www.example.com?p=paypalbuttonid
I would like to store and pass that "p" variable on to the next page. I don't want to pass the variable onto page 2 with a link. I would prefer to store the variable and recall it on page 2.
Page 1 code (above html):
<?php
session_start();
$_SESSION['paypal'] = $_GET['p'];
?>
Page 2 code (above html):
<?php
session_start();
$p = $_SESSION['paypal'];
?>
I'm calling the variable in a link on page 2 (body):
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=<?php echo $p ;?>" target="_blank" class="btn">
I'm not sure what I'm dong wrong but I'm a complete newbie to PHP so please help! The variable shows up blank in the URL on page 2. Thank you! - Chad
First, you should make sure you dont have any output before session_start(), it is safe to put session_start () at the top of the page , especially if you use php code in .html, since you may have output without awareness, and session wont work if you have anything output to the browser before session_start()
according to php.net:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
and you should check if you cookie is enabled.
Secondly, var_dump ($_SESSION); to see if you can get anything

php session variable

I have written code in PHP where I want to use session variable so that when I will click on submit button then I will get the same session variable after landing to the new page.
But session variable is showing empty after submit.
Below is my code:
session_start();
$i=6;
$_SESSION['testing1']=$_SESSION['testing'];
$_SESSION['testing']=$i;
but value for $_SESSION['testing1'] always shows empty.
1st time it will be empty but after clicking on submit button which is calling same page then it should not give empty value
You are setting $_SESSION['testing'] after $_SESSION['testing1']=$_SESSION['testing'];, so it is still empty while setting. Switch both statements around.
try this
session_start();
$i=6;
$_SESSION['testing']=$i;
$_SESSION['testing1']=$_SESSION['testing'];

Categories