PHP $_SESSION variables not storing values - php

I'm trying to use PHP session variables to carry data over multiple pages. I am using session variables on many parts of my site, but this is the first place where they don't work.
I'm setting it like this:
$_SESSION["savedRetailerName"] = $foo;
And calling it like this:
echo $_SESSION["savedRetailerName"];
The session id remains the same between these two pages, and I'm sure that I'm setting the variables right and that they are being called right. I start the session correctly, and even on that particular page, other session variables are being shown properly.
How can I begin to debug this odd behavior?
Edit:
There are two different pages I'm currently dealing with. Page 2 sets the session variables, and there is a button that will return the user to Page 1. The idea is to still have the fields in Page 1 filled in if the user wishes to return to Page 1.
It is not a cache problem, and I can return other session variables in the exact same spot in my code as where I am failing to return these variables.
The only other code that may be pertinent is the back button handler (jQuery):
$('#backButton').live('click',function() {
window.location.replace("page 1");
});
Edit 2:
I believe this isn't working because of something with variables here:
<?php
$retailerName = $_REQUEST["retailerName"];
$description = $_REQUEST["description"];
$savingsDetails = $_REQUEST["savingsDetails"];
$terms = $_REQUEST["terms"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$zone = $_REQUEST["zone"];
$dateExp = $_REQUEST["dateExp"];
$tag = $_REQUEST["tag"];
$_SESSION["rn"] = $retailerName;
$_SESSION["de"] = $description;
$_SESSION["sd"] = $savingsDetails;
$_SESSION["tm"] = $terms;
$_SESSION["ph"] = $phone;
$_SESSION["ad"] = $address;
$_SESSION["zo"] = $zone;
$_SESSION["ex"] = $dateExp;
$_SESSION["tg"] = $tag;
?>
I am able to set any session variable to a string, but it won't set to a variable.

You want to use session_start before you set or use any session variables. You only need to call it once.
If it's working in other places, odds are that this particular block of code is being executed before session_start is called.

remove all non printable characters before <?php
you may not see them..

You have spaces before your <php tag
You don't have session_start() anywhere
You are using the $_REQUEST variable which is sketchy (use $_GET or $_POST instead)

You would also need to register the session using
session_register # php.net

Related

how to add an array to a session php

I want to add different stuffs to costumers cart but before adding the stuff transition in the database costumer must pay and then redirect to another page after Successful transition i need the chosen stuffs id's i tried using $_POST but the browser does not send the post value because of payment system in the middle i tried using sessions instead
I want to add array of integers to a session control i already tried using this code
$t=array(1,2,3,4,5);
$_SESSION['exam_id']=$t
I don't know if i can do such a thing or not but what is the parallels
What you specified is working correctly. Sessions can hold arrays.
The session superglobal is an represented as an array itself within PHP, so you can just get and set values by doing the following
Setting:
$_SESSION['exam_id'][] = "new value";
or
$_SESSION['exam_id'] = array("new value", "another value");
Getting:
$_SESSION['exam_id'][0]; // returns a value
This returns the first value in the exam_id array within the session variable
You will need to start the session. Make your code;
<?php
session_start();
$t = array(1,2,3,4,5);
$_SESSION['exam_id'] = $t;
You need session_start()
You didn't have a semi-colon ; at the end.
you can use array in session like this..
you have to start session with session_start();
and then store your array to session $_SESSION['items'][] = $item;
and then you use it, whenever you want:
foreach($_SESSION['items'][] as $item)
{
echo $item;
}
You can set PHP sessions equal to an array just like you're doing.
To set the $_SESSION variable equal to all POST data, you can do this:
$_SESSION['exam_id'] = $_POST;
Be sure to add session_start() prior to declaring any session variables.
$t=array(1,2,3,4,5);
$_SESSION['exam_id'] = array();
array_push($_SESSION['exam_id'],$t[0]);
array_push($_SESSION['exam_id'],$t[1]);
array_push($_SESSION['exam_id'],$t[2]);
array_push($_SESSION['exam_id'],$t[3]);
array_push($_SESSION['exam_id'],$t[4]);

URL variable to Session variable (using GET method)

I am trying to store a value obtained from a URL variable into a SESSION variable.
Here is the URL:
Ace Hardware
Here is the SESSION coding, which retrieves the variable, but loses the variable value upon leaving the page.
$_SESSION["store"] = $_GET["store"];
$shopByStore = $_SESSION["store"];
If I plug in the value in quotes as it is below (see "Ace" in code below), it works. But it doesn't work in the code above using the GET method ($_GET["store"])
$_SESSION["store"] = "Ace";
$shopByStore = $_SESSION["store"];
The problem is that you override the $_SESSION["store"] with the $_GET["store"] each time whether the get request exists or not, so it basically only uses $_GET["store"]. You could use this instead:
if (isset($_GET["store"])) {
$_SESSION["store"] = $_GET["store"];
}
At first you need to start the session and then make sure it's already not stored in the session (if it's passed in the $_GET) and if not already saved in the session then store it:
// The first line in your script
session_start();
if (isset($_GET["store"])) {
if (!isset($_SESSION["store"])) {
$_SESSION["store"] = $_GET["store"];
}
}
Read more on PHP manual.

PHP session variables blank after page refresh

I wrote a post about this earlier and got good responses that corrected a mistake I had, which I thought fixed the problem. Unfortunately it didn't, and my old post is messy enough that I'm going to repost the problem, but with the added perspective I have gained struggling with this for another good while.
Code (simplified):
<?php
session_start();
if (!$_SESSION["companyid"]) {
header("location: http://www.somepage.com");
}
mysql_connect("localhost", "name", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$companyid = $_SESSION["companyid"];
$_SESSION["youtubeurl"] = mysql_real_escape_string($_POST["youtubeurl"]);
$_SESSION["logourl"] = mysql_real_escape_string($_POST["logourl"]);
$_SESSION["plan1head"] = mysql_real_escape_string($_POST["plan1head"]);
$_SESSION["plan1description"] = mysql_real_escape_string($_POST["plan1description"]);
$_SESSION["plan1headline1"] = mysql_real_escape_string($_POST["plan1headline1"]);
$_SESSION["plan1price1"] = mysql_real_escape_string($_POST["plan1price1"]);
$_SESSION["plan1headline2"] = mysql_real_escape_string($_POST["plan1headline2"]);
$_SESSION["plan1price2"] = mysql_real_escape_string($_POST["plan1price2"]);
$_SESSION["plan1price1type"] = mysql_real_escape_string($_POST["plan1price1type"]);
$_SESSION["plan1price2type"] = mysql_real_escape_string($_POST["plan1price2type"]);
if(isset($_POST["submitpreview"])) {
$companyid = $_SESSION["companyid"];
$youtubeurl = $_SESSION["youtubeurl"];
$logourl = $_SESSION["logourl"];
$plan1head = $_SESSION["plan1head"];
$plan1description = $_SESSION["plan1description"];
$plan1headline1 = $_SESSION["plan1headline1"];
$plan1price1 = $_SESSION["plan1price1"];
$plan1headline2 = $_SESSION["plan1headline2"];
$plan1price2 = $_SESSION["plan1price2"];
$plan1price1type = $_SESSION["plan1price1type"];
$plan1price2type = $_SESSION["plan1price2type"];
}
?>
Now, there are three pages/instances involved with this:
Page with forms that pass variables to a preview page
Preview page
Submitted preview page (meaning page is refreshed)
A person has their own page filled with various text fields and drop-down menus (page 1). They can update this page, and when they fill out the form to do that and submit it, those variables are passed onto the preview page. If they like the preview page, that confirm it (submitting a form that executes "submitpreview").
Here is my problem: All the session variables that are being filled by the form (everything but company id, which is stored in a session when they first log in) are immediately dumped into a session variable. I have echoed out those session variables at the bottom of the preview page (just to confirm they are not empty at this point in time), and their contents are echoed out appropriately when I get to the preview page. However, when the user confirms the changes and submitpreview is set, suddenly those session variables are empty. That is, all the session variables that were filled by the form variables are empty. The session variables that echoed out just fine before the page was refreshed are gone except for the companyid variable. Since the companyid session variable is still just fine, so I know that (1) sessions on my server must be working right and (2) the problem lies with the code that is either dumping the form variables into the sessions or retrieving those variables. Any theories as to why this may be occurring?
This has me pretty frustrated. I appreciate your patience with me on this issue and appreciate any help that is given.
Figured it out, thought I would share.
In instances such as this when your have session variables equal to post variables on a page that refreshes, you to have be careful. When my preview page would refresh, the post variables (since they no longer existed) became empty, which overwrote the information for the session variables I had previously saved and in turn made those session variables empty as well. I had to adjust my code accordingly to fix that problem.
The problem, as described in Pete_1s answer, is caused by register_globals. This results in the mixing of different variables with equal names .
This:
foreach ($_SESSION AS $name -> $value) {
unset ($_GLOBALS[$name]);
}
foreach ($_POST AS $name -> $value) {
unset ($_GLOBALS[$name]);
}
foreach ($_GET AS $name -> $value) {
unset ($_GLOBALS[$name]);
}
will solve the problem, if you have no means of deactivating register_globals.

How can I keep a shopping cart populated when the user navigates away from the 'cart' page, wihtout using a database

I am building a shopping cart with php, and i have all the items able to pass through to the cart page. However, if the user were to navigate away from the page, all the items disappear. I know that I can use to begin a session, but how do i persist data in the session without using a database?
Should I learn HTML5 session-storage?
Thanks, Eric. I agree, 'if it aint broke then dont try to fix it'...so, how exactly do I read/ write data to the $_SESSION array. I have read the php manual page, but still am at a loss...my data doesnt transfer. Here's my code:
<?php session_start();
$mytext = $_SESSION['mytext'];
$mytext1 = $_SESSION['mytext1'];
$mytext2 = $_SESSION['mytext2'];
$mytext3 = $_SESSION['mytext3'];
$price = $_SESSION['price'];
$price1 = $_SESSION['price1'];
$price2 = $_SESSION['price2'];
$price3 = $_SESSION['price3'];
$total = $mytext * $price;
$total1 = $mytext1 * $price1;
$total2 = $mytext2 * $price2;
$total3 = $mytext3 * $price3;
?>'
By default, the PHP $_SESSION variable doesn't use a proper database or need you to install anything in addition to PHP. It will simply store each users session data in a file on your server.
After calling session_start() you can simply read/write data to the $_SESSION array as you would any other array. Look at the session_start() page for an example.
No, I wouldn't do this in HTML 5. PHP sessions have been working well for years and won't have any browser compatibility issues.
EDIT
Are you writing to the array first? If you haven't put the items in, you won't get anything out. You'll notice that on the example in the linked page, there are two pages in play. The first page assigns to the session array. In your code, you only try to take things out of the session array. Until you add items to it, you won't get anything out of it.

PHP/HTML - isset function

I'm fairly new to PHP and am creating a website for my company. I am using some existing code that I have obtained but can't seem to make it work properly - any help would be much appreciated!
I have a variable, $id, which identifies the product category type to display on the page. I first need to check that the id variable has been set and if not, default the variable to category 0.
The code I have is as follows:
setdefault($id, 0);
function setdefault(&$var, $default="")
{
if (!isset($var))
{
$var = $default;
}
}
So with the address www.website.com/browse.php, I would expect it to default to $id=0; with the address www.website.com/browse.php?id=3, I would expect it to set $id to 3 and display the relevant products. However, despite setting $id, it still defaults to 0. Is there something obviously incorrect with my code?
You are probably expecting PHP to use the $_POST and $_GET as global variables. PHP used to be setup this way, back in the day, but newer versions require you to explicitly reference these variables.
You could try this:
setdefault($_GET['id'], 0);
function setdefault(&$var, $default="")
{
if (!isset($var))
{
$var = $default;
}
}
or even more simply (using the ternary operator):
$id = array_key_exists('id', $_GET) ? $_GET['id'] : 0;
First off, if this is PHP 5.X I highly recommend you do not pass variables by reference using the &. That being said. the isset function call will always be true withing the function. But you will receive an undefined variable warning on the setdefault($id, 0);
Try this instead.
$id = isset($id) ? $id : 0;
If $id is not set, the call to setdefault($id,0) will generate a warning. A function like setdefault does not work in PHP. Use this instead.
if (!isset($id)) $id = 0;
If you are doing this for array variables, like $_GET and $_POST, you can do this:
function getuservar($A, $index, $default = '') {
if (!isset($A[$index])) return $default;
if (get_magic_quote_gpc()) return stripslashes($A[$index]);
return $A[$index];
}
$clean_id = getuservar($_GET, 'id', 0);
This return form is better because you stop using the $_GET array immediately and only use the variables that are cleaned in the rest of the code. You clean your external variables once and never touch the external variables again in your code. $A can be $_GET, $_POST, $_REQUEST or $_COOKIE.
It also handles the annoying magic_quote stuff for you so you know the data in the variable is the text sent by the user. Just remember to clean it again when sending it back to the user or to the database.
How is $id being set? If register_globals is off (and it's off by default in PHP 4.2 and newer), you need to look at $_GET['id'] or $_POST['id'] instead (or $_REQUEST['id'], but there are reasons to avoid that).
The code to set $id to sometime from the query string (browse.php?id=3) would also need to be included. You might be thinking of the register_globals settings that PHP has that will automatically create variables when included in the query string. DO NOT re-enable that feature, for several years now that has been shown to be a really bad idea.
Any variable you are pulling from the query string needs to be checked for type/safety before using it. So for example you might pull the variable from the $_GET super global, check to see if it's numeric, if it is not then set the default:
if (!is_numeric($_GET['id']) {
setdefault($_GET['id'], 0);
}

Categories