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.
Related
I'm trying to create an interface where a workshop description can be updated on the server after it has been created by a user. There is a text field and a button that brings up the workshop by the number it was assigned. (This is also the name of the directory in the submissions/workshop# on the server). When I set the variable $workshopPath using this method, I want to be able to access this global variable when a text input is filled out with the string to update the title of the workshop. The $workshopPath is registering as an empty string in the 'updateTextItems' function, so it is writing the text file to the root directory instead of to the correct workshop directory. I thought I was correctly referencing the global variable within the functions, but this isn't working. I also tried using $GLOBALS['workshopPath'], but that isn't working either. Can someone help me figure out how to pass the variable to the second function? Thanks :-)
<?php
$workshopPath;
if (isset($_POST['gotoWorkshop'])) {
if (empty($_POST['numberInput'])) {
echo "Please enter a valid workshop number";
} else { //Assign the name variable form the posted field info if one was entered.
$workshopNumber = stripslashes($_POST['numberInput']);
global $workshopPath;
$workshopPath = "submissions/" . $workshopNumber . "/";
}
}
if (isset($_POST['updateTextItems'])) {
if ($_POST['titleInput']) {
//Assign the name variable form the posted field info if one was entered.
$titleInput = stripslashes($_POST['titleInput']);
}
if ($titleInput) {
global $workshopPath;
$titleFile = fopen($workshopPath . "title.txt", "w") or die("There was an error creating the title file.");
fwrite($titleFile, $titleInput);
fclose($titleFile);
}
}
?>
Do I understood you correct? The user fill in the a form for the workshop click submit and get an othewr form for the text? My guess is you sen to requests to the server. So $GLOBAL will not work for you. It only works per request and I think most time you do not realy need it. If you want to save some values across requests, you need a session when you start your session. After you have started your session with session_start() you can use $_SESSION[] to store and get your value
I am currently trying to pass a multidimensional array through sessions while also being able to dynamically add/remove from it (it is a wish-list). The index of the array will be the ID of an item I am adding to the array. I've tried serialization, using variables instead of the actual session and none of it worked properly for me.
My issue is that my array will not pass from page 1 to page 2. Page 1 is what happens when the user clicks any "add to wish-list" button
I searched up on Google and wrote something similar to this:
page 1:
session_start();
$_SESSION['wishlist'] = array();
$id = $_GET['id'];
$imageFileName = $_GET['ImageFileName'];
$title = urldecode($_GET['PictureName']);
$_SESSION['wishlist'][$id]=array("id"=>$id,"title"=>$title,"imageFileName"=>$imageFileName); // Here im making the multidimensional array
$_SESSION['wishlist'] = $_POST; //found this way on Stackoverflow
header('Location:view-wish-list.php'); //move to second page
page 2: trying to start session and print out the array to test:
session_start();
var_dump($_SESSION['wishlist']);
Var Dump gives me array(0) { }
Any help would be appreciated. Thank you.
You have to commit (write) the session before redirection or the second request may occur before the session data is available on the server:
session_write_close();
header('Location:view-wish-list.php'); //move to second page
Sorry if I'm duplicating threads here, but I wasn't able to find an answer to this anywhere else on StackOverflow.
Basically what I'm trying to do is make a list in which variables entered in a form by a user can be kept. At the moment, I have the code which makes this possible, and functional, however the variables entered in the form only appear on the list after the user hits submit... As soon as I refresh the page or go to the page from somewhere else, the variables disappear. Is there any way I can stop this from happening?
Edit: here are the codes:
//Page 1
<?php
session_start();
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
echo "<a href='Page 2'>Link</a>";
$_SESSION['entries_unique_values'] = $entries_unique_values;
?>
//Page2
<?php
session_start();
$entries_unique_values = $_SESSION['entries_unique_values'];
foreach($entries_unique_values as $key => $value) {
$ValueReplace = $value;
echo "<br /><a href='http://example.com/members/?s=$ValueReplace'>" . $value . "</a><br/>";
}
?>
Your question is really quite vague. the answer depends on how much data you have to store, and fopr how long you need it to exsist.
By variable I assume you mean data the user has entered and that you want to put into a variable.
I also presume that the list of variables is created by php when the form is submitted.
Php will only create the variable list when the form is submitted as php is done entirely on the server, therefore you will not have or see the variables until the form is submitted.
if you wanted to be able to see the list as it is being created you could use javascript then once you have you php variables the javascript list isn't necesary.
each time you request a php page wheather it is the same one or not the server generates a totally new page, meaning all unhardcoded variables from previous pages will be lost unless you continually post the variables around the pages the server will have no memory of them.
You have a few viable options.
) keep passing the user created variables in POST or GET requests so each page has the necesary info to work with. Depending on the situation it might or might not be a good idea. If the data only needs to exsits for one or two pages then it is ok, but bad if you need the data to be accessable from any page on your web.
2.) start a session and store the variables in a session. Good if the data only needs to be around while the user is connected to the site. but will be lost if user close window or after a time.
3.) place a cookie. not a good idea but ok for simple data.
4.) create a mysql database and drop the variable info in there. great for permanent data. this is how i always complex user data.
just a few ideas for you to look into as it is difficult to see what you really mean. good luck.
use PHP session or store variable values in Cookies via JS or using PHP. It would be nice if you show your working codes :)
Your idea is fine, however you just need to add a little condition to your Page 1 that only set your SESSION values when POST is made, that way it will keep the values even if you refresh. Otherwise when you visit the page without a POST those values will be overwritten by blank values, which is what you are seeing now. You can modify it like
<?php
session_start();
if(isset($_POST["signup_username"]))
{
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
$_SESSION['entries_unique_values'] = $entries_unique_values;
}
echo "<a href='http://localhost/Calculator/form2.1.php'>Link</a>";
?>
You could use JavaScript and HTML5 local storage.
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.
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