session array won't unset - php

I have this small script that runs after a user posts.
I have a $_SESSION['con29'][value] that I populate with data from the post.
This code should either add or remove an array element.
It adds an element fine, but I can't work out why it won't unset the $_SESSION array
if (isset($_POST['sub_search_content_id']))
{
$row_id_1 = $_POST['sub_search_content_id'];
$_SESSION['con29'][$row_id_1] = $_POST['sub_search_content_id'];
}
if (isset($_POST['sub_search_content_id_remove']))
{
$ss_id = $_POST['sub_search_content_id_remove'];
unset($_SESSION['con29'][$ss_id]);
}

Use !empty instead isset
because isset only will check variable is created or not
but !empty will check variable is empty or not too.
and if you don't have another session variables so you may try
session_unset();or session_destroy();
and you can also use
session_register($value);
and
session_unregister($value);
for this
Hope this helps

Related

PHP 5.6 unset $_SESSION sub array entry

I got the following function:
public function stopWatcherSession($sessionID) {
if(array_key_exists($sessionID, $_SESSION[self::WATCHER_SESSION_KEY])) {
foreach ($_SESSION[self::WATCHER_SESSION_KEY][$sessionID]['names'] as $v) {
$ptype = $this->paramTypeFromName($v);
unset($_SESSION[self::SESSION_KEY][$ptype][$v]); //does not work, sets entry to null
}
unset($_SESSION[self::WATCHER_SESSION_KEY][$sessionID]); //does not work, sets entry to null
}
}
As the comments say, the array entry does not get unset, the array_key_exists()-function still returns true, and if you var_dump($_SESSION) you can see, that $_SESSION[self::WATCHER_SESSION_KEY][$sessionID] is null.
How can I unset the variable, so that also the key in the array gets removed?
Things i tried, that did not work:
// v1 (tried also for `$_SESSION[self::WATCHER_SESSION_KEY][$sessionID]` )
$tmp = $_SESSION[self::SESSION_KEY][$ptype];
unset($tmp[$v]);
$_SESSION[self::SESSION_KEY][$ptype] = $tmp;
//v2
unset($_SESSION[self::WATCHER_SESSION_KEY][$sessionID]);
session_write_close();
session_start();
//v3 => v1 & v2 combined
$tmp = $_SESSION[self::SESSION_KEY][$ptype];
unset($tmp[$v]);
$_SESSION[self::SESSION_KEY][$ptype] = $tmp;
session_write_close();
session_start();
I could add a crappy hack all over the code to check whether it's null, but then »empty« values must be changed to something else (like a predefined const, but thats a nasty workaround and leads to confusion for other devs!)
Anyone got some ideas?
Got it working:
unset($GLOBALS['_SESSION'][self::WATCHER_SESSION_KEY][$sessionID]); does the job.
http://php.net/manual/en/function.unset.php says:
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. […] To unset() a global variable inside of a function, then use the $GLOBALS array to do so
Seems like a classical »PHP behaviour is undefined in some cases«-example.

How to Print a variable in a function in PHP

I have a form, with post="ModelSelector", when submitted, we go through these codes.
Issue I'm facing is, I want to check the value of $_POST, I know it is getting set by calling "isset()".
I just want to Print/alert/pushout the variable $productselection
function selectProduct() {
// save the post in a variable
$ProductSelections = $_POST['ModelSelector'];
// I want to print $ProductSelection to check its value
$frmVars['ProductSelections'] = $ProductSelections;
$frmVars['WindowSize'] = $WindowSize;
$frmVars['PageNum'] = 1;
saveFormValues(0,'RunDefMgr', $frmVars);
// Clear the checkboxes
$sel = array();
deleteRunDef(0,"*","RUN_DEF_EDIT","*");
}
if(isset($_POST['ModelSelector'])) {
selectProduct();
}
I have tried ECHO, for some reason it is not printing the value in HTML.
Thanks in advance.
I want to check the value of $_POST
$_POST will be an array.
Use print_r($_POST) or var_dump($_POST) to view its contents.
Your form method should be method="POST", You can use the following edit to see if it works , as you have to pass $_POST (array) to the function to use it inside function. function expects an parameter else , $_POST does not exists.
And also enable the errors inside your file to check which type of errors you are getting by using : ini_set('display_errors',1); or error_reporting(E_ALL);
function selectProduct($_POST) { // create parameter $_POST which we get from isset condition.
// save the post in a variable
$ProductSelections = $_POST['ModelSelector'];
print_r($ProductSelections); // print the value.
// I want to print $ProductSelection to check its value
$frmVars['ProductSelections'] = $ProductSelections;
$frmVars['WindowSize'] = $WindowSize;
$frmVars['PageNum'] = 1;
saveFormValues(0,'RunDefMgr', $frmVars);
// Clear the checkboxes
$sel = array();
deleteRunDef(0,"*","RUN_DEF_EDIT","*");
}
if(isset($_POST['ModelSelector'])) {
selectProduct($_POST); // pass the $_POST array to the selectProduct function.
}

Why is my session not holding its data?

I've never run into this before but for some reason, when I am using AJAX to set a session variable, the session will not hold them.
Here is what I have:
session_start();
if(isset($_POST['selected'])){
$_SESSION['user']['theme'] = array ('selected' => true);
} // This should be now set with the value and it is for a time, but unsets
if(isset($_POST['theme'])){
$_SESSION['user']['theme'] = array('name' => $_POST['theme']);
} // So should this
What I am seeing when I do a print_r under both if constructs is only the $_SESSION['user']['theme']['name'] var and the other is not set. If I do a print_r just under the selected var, I can see it just fine. Somewhere, the key and value are disappearing for selected.
Why is this happening? I'm expecting to see both name and selected.
Like i said in my comment, you're overriding the array :)
session_start();
//changed it to unset if not in $_POST
$_SESSION['user']['theme']['selected'] = isset($_POST['selected']);
if(isset($_POST['theme'])){
$_SESSION['user']['theme']['name'] = $_POST['theme'];
} // and unset it too
else {
$_SESSION['user']['theme']['name']= "";
}
You need to start the session first
session_start();
if(isset($_POST['selected'])){
$_SESSION['user']['theme'] = array ('selected' => true);
}
And also check whether the $_POST values are not empty.And you need to unset the name in session then assign it like
if(isset($_POST['theme'])){
unset($_SESSION['user']['theme']['name']);
$_SESSION['user']['theme'] = array('name' => $_POST['theme']);
}
At the start of any page that sessions variables are accessed in any way, the first command must be a call to session_start();

Any easier way to do $name = $_REQUEST["name"];?

So I'm new to PHP and am trying to create a form. I accept a bunch of parameters and want to process them in the same page. I'm not sure how to do this without a giant if-else containing the entire page as if($_POST). This doesn't seem ideal.
In addition, I'm finding that I do the following a lot. Is there any way to shorten this? The names all remain the same.
$name = $_REQUEST["name"];
$gender = $_REQUEST["gender"];
$age = $_REQUEST["age"];
And I have a lot of lines which are just doing that, and it seems terribly inefficient
You can use the extract() function to do that. But it has a security downside: existing variables can be overwritten if someone would add variables to the POST header.
Edit: hsz's solution is better
What process you are doing with if..else..if you have to post the code so that we can let you know how that can be shorten.
you can avoid the assignment for each variable using extract function.
extract($_POST);
But be aware that can overwrite your existing variable if the are named same as your input controls.
Stop using $_REQUEST, because it is a combination of $_COOKIE , $_POST and $_GET.
It becomes a security risk.
Instead of using $_REQUEST you should use $_POST here.
$keys = array('name', 'gender', 'age');
foreach ( $keys as $key ) {
if ( isset($_POST[$key]) ) {
$$key = $_POST[$key];
}
// optional:
else {
$$key = ''; // default value
}
}
Magic quotes? http://php.net/manual/en/security.magicquotes.php
For the first thing: Turn it around. Don't do
if ($_POST) {
// Your handling code
} else {
echo "No data!";
}
do
if (!$_POST) {
die("No data!");
}
// Your handling code
You can use extract(), however, this means that you're bringing in a lot of variables that you (might not know about) int your current scope.
My suggestion would be to loop through your array and do something with the variables in there (e.g. - validation)
foreach ($_POST as $key => $valu) {
//do something with the variables
}
Also, don't use $_REQUEST unless you really want to check $_GET, $_POST and $_COOKIE. Use the proper array when accessing variables or people can send data you don't expect.

PHP $_SESSION Array Problem

I am just trying to write a function in php that adds to the discount array but it doesn't seem to work at all.
function addToDiscountArray($item){
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Every time I refresh the page it acts like $_SESSION["discountCalculator"] hasn't been set up but I can't understand why. Whilst writing can I use the $_SESSION["discountCalculator"] in a foreach php loop in the normal way too?
Many thanks
The fact that every time $_SESSION['discountCalculator'] seems not to be set, could be because $_SESSION is not set (NULL). This case happens mostly when you did not executed session_start() at the beginning of you page.
Try adding session_start() at the beginning of the function.
function addToDiscountArray($item) {
if (!$_SESSION) { // $_SESSION is NULL if session is not started
session_start(); // we need to start the session to populate it
}
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Notice that this will not affect the function if the session is already started. It will only run ´session_start()` if the session is not started.

Categories