I have a question regarding a session variable.
I have session variable which needs to start at a default variable. Then I need to be able to pass a new one through $_GET and keep that updated. So that even if the user reloads the page, it does not go back to the default value. How might I go about doing this? Thanks!
With this snippet you'll have session variable assigning once:
if (!isset($_SESSION['magic'])) {
$_SESSION['magic'] = isset($_GET['magic']) ? $_GET['magic'] : 1;
}
Seems like something along these lines might work:
if(!isset($_SESSION['my_parm']))
{
$_SESSION['my_parm'] = 'DEFAULT';
}
if(isset($_GET['my_parm']))
{
$_SESSION['my_parm']=$my_parm;
}
Use
session_start();
$_SESSION
below is the link for session manual
http://www.php.net/manual/en/reserved.variables.session.php
If I understood well, this would be an outline of your method:
<?php
session_start();
if (isset($_GET['my_variable'])) {
$_SESSION['my_variable'] = $_GET['my_variable']; // force new value
}
if (!isset($_SESSION['my_variable'])) {
$_SESSION['my_variable'] = $default_value; // initialize
}
update_value($_SESSION['my_variable']);
Related
I am a still a newbie when it comes to using YII, but I been working with session variables for the past few days, and I can't seem to grasp to the concept behind my error. Any advice will be appreciated.
My add function works perfectly so far, for my current purpose of keeping track of the last 3 variables added to my session variable nutrition.
public function addSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
Yii::app()->session['nutrition'] = array();
}
$nutrition = Yii::app()->session['nutrition'];
array_unshift($nutrition, $pageId);
array_splice($nutrition, 3);
Yii::app()->session['nutrition'] = $nutrition;
}
My remove function doesn't seem to work at all, no matter what I try to do with it. The reason why I am transfering the session array to a temp array was to try to get around the "If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called." But it was a total failure.
public function removeSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
return true;
}
$nutritionArray = Yii::app()->session['nutrition'];
unset($nutritionArray[$pageId]);
Yii::app()->session['nutrition'] = $nutritionArray;
}
Any advice or push toward to the correct direction will be appreciated.
I personally I have never used Yii::app()->session I normally use the Yii user and I have never had any issues with it:
Yii::app()->user->setState('test', array('a'=>1,'b'=>2));
print_r(Yii::app()->user->getState('test')); //see whole array
$test = Yii::app()->user->getState('test');
unset($test['b']);
Yii::app()->user->setState('test',$test);
print_r(Yii::app()->user->getState('test')); //only 'a'=>1 remains
Yii::app()->user->setState('test', null);
print_r(Yii::app()->user->getState('test')); //now a null value
As I put in a comment above there seems to be issues with multidimensional arrays with the session variable: https://code.google.com/p/yii/issues/detail?id=1681
I'm trying to pass a value between 2 pages through a $_SESSION variable then empty it as follows:
I'm assigning the session variable with a value on one PHP page:
$_SESSION["elementName"]="a_373";
And trying to store it in a variable on another page as follows:
if (!empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
The value of $elemName is always empty when I print it out. However, I get the correct printout when I remove the $_SESSION["elementName"]=""; line from the above code.
Edit: I'm printing $elemName and not $_SESSION["elementName"] - print($elemName);
I'm on a shared hosting account with PHP 5.3.2 and register_globals set to off (as per phpinfo();).
I need to reset/empty the session variable once I get the value it has, but it's not working and this has been baffling me for the last couple of days. Any ideas why? Thanks!
EDIT:
Additional clues: I tested with the session's var_dump before the if statement and set another value for $elemName in the else section as follows:
var_dump($_SESSION["elementName"]);
$elemName="x";
if (isset($_SESSION["elementName"]) && !empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="None";
}
print("<br />".$elemName);
I got this result:
string(5) "a_373"
None
Try using isset($_SESSION["elementName"]) and unset($_SESSION["elementName"]) instead.
Check the Below code and test it
if (isset($_SESSION["elementName"]) && $_SESSION["elementName"]!="") {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
Empty only check value is empty or not, But by isset we can check varaible exit and does not content empty value
Are you printing out $elemName? If yes than there shouldn't be any blank output unless and until your else condition returns true, but if you are printing $_SESSION["elementName"] than you'll get no output as you are making it blank
$_SESSION["elementName"]="";
Correct way to remove a session var completely is to use unset($_SESSION["elementName"])
Though if you want to make it empty, == '' is enough
Also be cautious while using unset() because after you unset the session and later use that index to print, it will show you undefined index error.
Update(As #nvanesch Commented)
I guess your else condition is getting satisfied, because you are
using $elemName=""; in your else, thus you are not returned with any
output
Also if (!empty($_SESSION["elementName"])) { will return false if you are not using session_start() at the very top of your page
I once created this class in order to be able to have this ability, and it works wonderfully:
<?php
class Flash {
public function set($key, $message) {
$_SESSION["flash_$key"] = $message;
}
public function get($key) {
$message = $_SESSION["flash_$key"];
unset($_SESSION["flash_$key"]);
return $message;
}
public function has($key) {
return isset($_SESSION["flash_$key"]);
}
}
It's pretty similar to what you're trying to do, so I'm not sure why it's not working for you, but you may want to give it a try. You obviously need to have the session already started.
When I check my cookies I do see that PHPSESSID is being made. But when I try to use them I get an error message saying that the variable is undefined.
This is how I set my Sessions:
$posts = array("auto_year", "auto_brand", "auto_model", "auto_bodywork", "auto_doors",
"auto_fuel", "auto_gearbox", "auto_type", "auto_uitvoering", "auto_part", "auto_description", "email_address");
//Define POSTS and set into SESSIONS
foreach ($posts as $post) {
if (isset($_POST[$post])) {
$_SESSION[$post] = $_POST[$post];
$$post = $_SESSION[$post];
}
}
I also tried it manually like:
$_SESSION['auto_year'] = '2012';
But it still doesn't work. I did call session_start() on top of the pages of both but it just keeps giving me that error.
using ${} you can create dynamic variables. In your case just change to:
${$post} = $_SESSION[$post];
Another option is to create the variables using extract() which enables you to set all variables in one go;
extract($_SESSION);
Will create a variable for each key in the session, e.g. $auto_year, $auto_brand, etc.
http://php.net/manual/en/function.extract.php
note
I'm wondering why you want to have all data in separate variables, whereas a single associative array may be just as easy to handle?
It's likely something wrong with the $_POST data coming from your form. As I don't have form info, I tried this by setting $_POST.
session_start();
$_POST['auto_year'] = 1977;
$posts = array("auto_year", "auto_brand", "auto_model", "auto_bodywork", "auto_doors",
"auto_fuel", "auto_gearbox", "auto_type", "auto_uitvoering", "auto_part", "auto_description", "email_address");
//Define POSTS and set into SESSIONS
foreach ($posts as $post) {
echo $post."<br>";
if (isset($_POST[$post])) {
echo "Creating variable for $post<br>";
$_SESSION[$post] = $_POST[$post];
$$post = $_SESSION[$post];
echo '$auto_year: '.$auto_year . "<br>";
}
}
echo "<br><br>".var_dump($_SESSION);
I have the following segment of code that someone else has written, and that I'm trying to fix:
function calc() {
require_once("db.php");
connect();
$a = split("#", $_SESSION['freight']);
$loc = $a[0];
$r = mysql_query("SELECT `price`, `gst` FROM `freight` WHERE `location`='$loc'");
$arr = mysql_fetch_array($r);
$_SESSION['freight'] = $loc."#".$arr['price'];
return $arr['price'];
}
function ajaxFunction () {
$_SESSION['freight'] = $_GET['loc'];
$freight = calc();
echo number_format($freight, 2);
return;
}
It ain't pretty, I am just trying to fix it.
Now I have noticed the bug seems to stem from the fact $freight = calc(). After that line, $freight will equal say $10 (the $arr['price'] value). BUT the $_SESSION['freight'] will also equal $10, and just $10, as if it was the same variable as $freight. What ever I set $freight to, the $_SESSION['freight'] also becomes.
If I change $freight in the ajax function to $freight2 it doesn't alter the session variable. Is this something major that I don't know about PHP? That variable names share the same namespace as session variables?
The question overall is:
Does changing $a alter $_SESSION['a'] in anyway? Because it really seems like it does.
It looks like your register globals is set to on in your php.ini file. You need to turn that off. If it's on, your $_SESSION, $_GET, $_POST elements can be referred to as the variable names.
e.g. $_SESSION['item'] is the same as $item
More info here: http://us2.php.net/manual/en/ini.core.php#ini.register-globals
Also, register globals is now deprecated, which also means that if this is indeed the issue, you were using an older version of PHP, and may want to consider upgrading.
As far as I can tell...
your $_SESSION variable should not be a session variable at all as it always equals $_SESSION['freight'] = $loc."#".$arr['price'];
I actually do not understand the use of the session so this is whow i would have approach it
function calc($loc)
{
require_once("db.php");
connect();
$r = mysql_query("SELECT `price`, `gst` FROM `freight` WHERE `location`='$loc'");
$arr = mysql_fetch_array($r);
$_SESSION['freight'] = $loc."#".$arr['price'];
return $arr['price'];
}
function ajaxFunction ()
{
$a = split("#", $_GET['loc']);
$freight = calc($a[0]);
echo number_format($freight, 2);
return;
}
You only need the location so that you can run your queries. So just set the session once with the new data from the database.
Hope that helps
I always use different notation for session variables. For example $_SESSION['_uid'] versus a regular $uid variable.
I'm trying to unset a certain value in a session array in php. I would like to ask if there's a better way in doing this:
<?php
session_start();
if(isset($_GET['Uname'])){
echo "Uname is set!";
$uname=$_GET['Uname'];
echo count($_SESSION['user']);
for($x=0; $x < count($_SESSION['user']); $x++ ){
if($_SESSION['user'][$x]['Uname']==$uname){
unset($_SESSION['user'][$x]['Uname']);
}
}
}else{
}
?>
Is it possible to accomplish the same thing using a foreach loop?Or another method
Sure unsetting user should solve that. You don't need a loop. Try this, refreshing page will surely set value at one time and other unset it's value.
<?php
session_start();
$array = array('arr', 'arr', 'arr', 'arr', 'arr', 'arr');
if(isset($_SESSION['user']))
{
print_r($_SESSION['user']);
unset($_SESSION['user']);
}
else{
$_SESSION['user'] = $array;
echo "user session was set";
}
And according to this question, https://stackoverflow.com/questions/4891301/top-bad-practices-in-php , using count() in loop is a bad practice.
I'm trying to unset a certain value in a session array in php. I would like to ask if there's a better way in doing this.
I can assure you that the best way to unset a variable is to use unset() function on it.