Session variables not available in a started session across pages - php

The goal is to persist some data between pages after a refresh when a user selects a db search filter criteria from 6 select dropdown boxes on the page using session_start() and the SESSION variables are set to the 6 select-box values the user selected, as a search button is clicked calling a Laravel controller action, where the SESSION is session_start() being begun and the 6 select-box variables are being set for the SESSION.
The goal is to reset the select boxes from session variables populated when the search button is clicked retaining the select box selections-criteria selected by user so they do not have to reselect the 6 select-boxes again. Those select-box selection values are stored in session variables;
Upon refresh after a successful search is being returned the SESSION variables are read in the masterlayout.blade html section to programmatically to reselect the previous search-filter selection the user had entered as the retrun page is rendered with the masterlayout.blade including the nav.blade.
In the masterlayout.blade (which includes the nav.blade which has the select-boxes) in the Laravel template system is where I READ these SESSION variables upon refresh of a user-search, then the SESSION variables set from the controller called from the button click reset the select boxes to values in the SESSION vars.
But, that masterlayout.blade template is called from other pages as it and search-nav appear on other pages which may be used for a search or not, before or after a user has done a filtered search.
The problem is when other pages are requested, even after a search, the SESSION variables seem to be unavailable, reset to nothing or whatever--- I cannot figure out as I did not destroy the session and they should be available from any page after being set.
But I get the _SESSION variables unavailable error when other pages are requested.
If you know how to fix this let me know.
If you know how to persist the select-box values between pages in a better manner let me know. I don't want to right to a db to do this, but maybe there is a javascript way to retain variables across pages.
Thanks

This is in the controller accessing post data from button click which calls the controller
//colvals
session_start();
$bidded=$_GET["bidded"];
$_SESSION["bidded"] = $bidded;
$state=$_GET["state"];
$_SESSION["state"] = $state;
$city=$_GET["city"];
$_SESSION["city"] = $city;
$biddertype=$_GET["biddertype"];
$_SESSION["biddertype"] = $biddertype;
$job=$_GET["job"];
$_SESSION["job"] = $job;
$subjob=$_GET["subjob"];
$_SESSION["subjob"] = $subjob;
In the search filter navigation page the select box values from previous user search (stored in above code from controller) is set by this:
<script>
document.getElementById("bidded").addEventListener("load", mySelect());
document.getElementById("state").addEventListener("load", mySelect());
document.getElementById("city").addEventListener("load", mySelect());
document.getElementById("biddertype").addEventListener("load", mySelect());
document.getElementById("job").addEventListener("load", mySelect());
document.getElementById("subjob").addEventListener("load", mySelect());
function mySelect() {
document.getElementById("<?php echo $_SESSION['bidded'];?>").selected = "true";
document.getElementById("<?php echo $_SESSION['state'];?>").selected = "true";
document.getElementById("<?php echo $_SESSION['city'];?>").selected = "true";
document.getElementById("<?php echo $_SESSION['biddertype'];?>").selected = "true";
document.getElementById("<?php echo $_SESSION['job'];?>").selected = "true";
document.getElementById("<?php echo $_SESSION['subjob'];?>").selected = "true";
}
</script>
Javascript session and local variables are not of any use in this case because when the page refreshes it reads the default state of the select boxes and overwrites the ones stored prior to the search input submission.
The problem was other pages would use the same template and complain about no _SESSION vars defined, when I did not destroy the session, but I guess only one script can access it, even if those pages have none. It requires a form submit to set the session filter select vals again.
Because this is a unique function it may end up having its own template as worrying about 100 other pages session vars is more of a PITA than a second template. I'll give cookies a shot but did not want to expose query data on user end.
Thanks for the input...

Related

PHP Session Values always one submission behind. How to get current values?

Have a project where a user fills out a succession of forms in a multi-step process. Each of the form screens have a next/back button that does an AJAX call and does a POST to a PHP controller. The PHP Controller then writes the form data to SESSION.
I need to insert a test for a certain state. Let's say the user selects 'California' as a state. If so, then they are taken OUT of the flow and shown another page that is an error/info page. Part of the functionality of this page is that it needs to take the stored Session values and write to a MySQL table (first_name, last_name, email)
So far so good. Part of my confusion is WHERE is the proper place to test for this value. Since we are MVC, I could test for it at the AJAX/JS level, or do the test in the controller. I chose to just test directly after the POST:
// If the customer has chosen CA as a state we must stop process
if ($('#employee_state_origin').val() == 'CA') {
PAGE_STATUS.destination = 'error-page';
}
The code uses PAGE_STATUS.destination as a way to keep track of what page is coming up next, what page is behind, etc. etc. Basically a keep-alive sort of history.
The problem is this. Once I do this test, of course the POST has already happened, and the controller puts the values in SESSION like so:
private function storeUserData(&$posted_data, &$user_input)
{
if ($this->response_body->has_error) {
return;
}
//If we just got data posted from employee entrance and it already exists - we need to reset all the data
if ($posted_data->step === 'employee_entrance' && !empty($_SESSION[SELF::SESSION_KEY][$posted_data->step])) {
$_SESSION[SELF::SESSION_KEY] = array();
}
if ($posted_data->step === 'member_information' || $posted_data->step === 'physician_information') {
$user_input->createCustomObject($posted_data);
$_SESSION[SELF::SESSION_KEY][$posted_data->step][] = $posted_data;
} else {
$_SESSION[SELF::SESSION_KEY][$posted_data->step] = $posted_data;
}
}
After the data is posted and written into SESSION the page redirects and shows the error page. On the error page, I am writing procedural code to dump into a MySQL table.
The issue is when I first start the browser, of course the Session is empty. I go to the form, put in first_name, last_name and email and then hit Next... the Ajax call happens, the POST values are good, the Session gets written....
But after the redirect, on the error page I have to start the session...
session_start();
$first_name = $_SESSION['wonderousBooksProject']['employee_entrance']->employee_first_name;
The problem is $first_name is empty when echo-ing it out as well as the other values. If I go to the page again, and put in different information and then go to the error page again.... it prints out the PREVIOUS ENTRY.
So, it's saving the session information, but my target page will not retrieve the latest entry...it retrieves the one previous.
Anyone have a thought about what is happening. I have used session_destroy() to end session, session_write_close(), and lots of other things, but cannot understand why it writes the session value the first time, shows it as blank, then the next entry is persona non grata and it displays the previous one?

passing varables' value from one form to another in php

I have three forms - payment.php , payment1.php and paydb.php . payment.php contains the front end form.payment1.php contains the back end of the form of payment.php. whereas we are shifting to paydb.php from payment1.php. Now I'm filling the form by entering member number in payment.php which is retrieved in a variable $member_no in payment1.php .Now I want to get the value of member_no in paydb.php . How to do that ?
After receiving $member_no in payment1.php redirect to paybd.php with a get array
using
header('Location: http://www.example.com/paydb.php?member_no=$member_no');
then receive $_GET['member_no'] number and assign to a variable
example:
$member_no = $_GET['member_no']
The first thing is make sure you are not passing sensitive information where the public can see it. Such as in a URL.
As soon as you get the member's number... store it in a session variable.
You can probably do this when they log in.
session_start();
$_SESSION['member_no'] = $member_no;
OR on the first payment page (assuming 'member_no' is the name of the form element being passed) like this...
$_SESSION['member_no'] = $_POST['member_no'];
Now that session will persist as long as the visitor has their browser open and you don't have to worry about passing it from page to page.
You can use that session on any subsequent page simply by calling it.
<?php echo $_SESSION['member_no'] ?>
Without showing this information to the public.
ALWAYS make sure you place this at the top of any page where you want to use session variables.
if (!isset($_SESSION)) {
session_start();
}

pass session values in pagination

I can pass values form one page to another but I need to pass value like this,
Page 1:
Page2.php
Page3.php
I need to pass the radio button values in the Page1.php to Page2.php, and also i need to use same session . if the form is redirected to page3, I am unable to get the value of page 1. its online quiz project. I tried session, form post method and few other methods but I am yet to succeed.
I would be very happy if you can help me with the code or some suggestions.
Thanks!
The best practice would be to go with OOP. So, you can do the following:
Create a class with fields to hold all the information you want to pass.
class PageInfo
{
var $pageTitle;
var $currentPage;
var $btnValue;
.....
}
2.Now crate an object of PageInfo class, and assign the values you want to set.
$page = new PageInfo();
$page->pageTitle = "Home";
$page->btnValue = 1;
...
3.Assign this object (holding all the details of your page) to the super-global session variable.
// store session data
$_SESSION['page'] = $page;
4.Now you can access the value stored in the session at the different pages.
$otherPage = $_SESSION['page'];
echo $otherPage->pageTitle;
echo $otherPage->btnValue;
Note: The session_start() function must appear BEFORE you print anyting on the page.
Actually your question is vague, first of all when you are using sessions, you need to be sure you are calling session_start() at the very top of the page, secondly, you can save the form data in your session variable like
if(isset($_POST['YOUR_SUBMIT_BUTTON_NAME_HERE'])) {
$store_temp_val1 = $_POST['whatever']; //Sanitize the value first
$_SESSION['page_one']['first_val'] = $store_temp_val1;
}
Now you can simply retrieve the value stored in the session variable on the second page like
echo $_SESSION['page_one']['first_val']; //Will echo the previous page value
Note: Use session_start() on each page at the very top.

Doubt with retrieving values

I have created a page with name edit.php. I have moved on this page from action.php using a edit button. I have successfully retrieved the values in the respective text boxes and other form items. I have problem that if by mistake this edit.php page is refreshed all values are gone. What is other way to maintain the values? Though thing are going well if page is not refreshed. If session variable is created than how values are retrieved of both that is of session variable and from database?
What I have did with problem.. I have requested "albumid" on action.php page..
session_start();
$aid = mysql_real_escape_string($_REQUEST['albumid']);
Now if action.php page is requested through edit.php page using edit button. than I have created a session variable. and destroyed it after successful update query.
if (isset($_POST["edit"])) {
$_SESSION["aid"]=$aid;
$result= mysql_query("SELECT * FROM table WHERE a_id =".$_SESSION["aid"]) or die(mysql_error());
$row=mysql_fetch_array($result); }
It means now session is created.. if page is refreshed than also session values remains and accordingly values are selected from this variable.
if($_POST['update']!="") {
Update query
session destroyed }
Than also my problem is not solved that is if page is refreshed before hitting update button I am loosing all values.
session variables are just data you put into the $_SESSION superglobal. Accessing them is no different than accessing any other array, except that the session array is saved for you automatically. All you need to remember is to do a session_start() before doing anything with the session.
$_SESSION['formfield1'] = $_POST['formfield1'];
$_SESSION['formfield2'] = $_POST['formfield2'];
etc...
<input type="text" name="formfield1" value="<?php echo htmlspecialchars($_SESSION['formfield1']) ?>" />
By default, PHP uses file-based sessions. To put it into a database, you'd have to write your own session handlers and point PHP to them using session_set_save_handler().
When you submit, save the values in appropriately named $_SESSION members. Then on your page, if you can't find the members in $_GET/$_POST, you can choose to look them up in $_SESSION. Or vice versa. Every time the user submits a form though, you should always update $_SESSION so that the values are the most current. (in case they backtrack, or resubmit, or whatnot).
session_start();
if (!empty($_POST)) {
$_SESSION['post'] = $_POST;
}
elseif (empty($_POST) && !empty($_SESSION['post'])) {
$_POST = $_SESSION['post'];
}
just don't forget to unset($_SESSION['post']); when you're done with it.
If I have understood your question correctly, I think you need some variables from database as well as from the session.
Simply put the key of your database tuple (or keys in case of multiple values) along with other stuff. Page, upon loading will check for the session variables and when it finds the key, it can use it to retrieve the data from the database.
In your previous page, the code will look like this :
$_SESSION["player_key"] = 56;
$_SESSION["tournament_key"] = 100;
And current page, start processing like this :
<?php
session_start();
$player = $_SESSION["player_key"];
$tournament = $_SESSION["tournament_key"];
/*
* your database connection steps
*/
$query = "select * from player where pid=".$player;
$res = mysql_query($query);
/*
Now assign values for your forms/components here or anywhere in the page. You don't have to read anything from the querystring.
*/
?>

Variable persistence in PHP

i have a php page,
on that page i have text boxes and a submit button,
this button runs php in a section:
if(isset($_POST['Add'])){code}
This works fine here and in that section $name,$base,$location etc are calculated and used. but that section of code generates another submit button that drives another section of code.
it is in this second section of code that i wish to add data to the DB.
Now i already know how to do this, the problem is that the variables $name and so forth have a value of NULL at this point.. but they can only be called after the first code section has been run where they gain value.
How do i maintain these values until the point where i add them?
Resources:
the page feel free to try it out:
location mustbe of the form 'DNN:NN:NN:NN' where D is "D" and N is a 0-9 integer
http://www.teamdelta.byethost12.com/postroute.php
the code of the php file as a text file!
http://www.teamdelta.byethost12.com/postroute.php
lines 116 and 149 are the start of the 2 button run sections!
I think you are looking for PHP's session handling stuff ...
As an example, first page:
session_start(); # start session handling.
$_SESSION['test']='hello world';
exit();
second page:
session_start(); # start session handling again.
echo $_SESSION['test']; # prints out 'hello world'
Behind the scenes, php has set a cookie in the users browser when you first call session start, serialized the $_SESSION array to disk at the end of execution, and then when it receives the cookie back on the next page request, it matches the serialised data and loads it back as the $_SESSION array when you call session_start();
Full details on the session handling stuff:
http://uk.php.net/manual/en/book.session.php
Around the add-button you are creating a second form. If you want to have the data within this form then you will have to create hidden input fields. Because you are sending a second form here. Or you are moving the add button up to the other form.
Or as others are mentioning.. Save the values into a session.
you could store them in a session
// first part of form, store name in session
$_SESSION['name'] = $_POST['name'];
// 2nd part of form, store in database
$name = mysql_real_escape_string($_SESSION['name']);
$sql = "INSERT INTO table (name_column) VALUES ('$name');
You can also try using hidden forms variables to store the data

Categories