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.
Related
[PHP 7.1]
Below you can see my PHP code. My problem comes from my difficult to understand why the second IF statement doesn't work with the array $_SESSION['items'], but does work with the testing array $zoo (I just created $zoo to make tests in place of $_SESSION['items']).
I've an AJAX script that send POST data to the PHP code and then logs the response to the browser console in order to let me review the results. Everything was working fine with my tests, all changes done to other arrays where executed with fine results, the only issue I couldn't understand and solve, even after extensively searching for some clues on the web and trying different things, is the misterious ways of the $_SESSION array that doesn't seem to like to expose its keys to lurking IF statements... And I got here trying to detect the existence of a key inside an array in order to increment its value. Something I already did before with other arrays that weren't $_SESSION arrays and it worked just fine.
session_start();
$_SESSION['items'] = array();
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['item_name'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
This is a simplified version of your code with just the important stuff
session_start();
$_SESSION['items'] = array(); //items is now emtpy
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
}
This should make it a bit easier to see, so it's simply because items is an empty array. Do to assigning it as such before the condition.
To fix it, either remove this line:
$_SESSION['items'] = array();
OR better yet:
$_SESSION['items'] = isset($_SESSION['items']) ? $_SESSION['items'] : [];
OR even
if(!isset($_SESSION['items'])) $_SESSION['items'] = [];
It's up to you how you fix it, but I am certain you don't want to reset that to an empty array. It's a very easy mistake to make, and a hard one to find because it's technically legal PHP code. I just have a built in debugger in my head now, from years of coding ... lol ... Most times I can literally picture in my mind how something will execute.
Cheers!
As noted by #artisticphoenix -
session_start();
// Check to see if there is a session variable before clearing it
// You only want to initialize it once
if (!isset($_SESSION['items'])) {
$_SESSION['items'] = [];
}
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
// This test is sufficient to check if the session variable has been set
if (isset($_SESSION['items'][$_POST['item_name']])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['items'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
$_SESSION['item_name'] should be $_SESSION['items']
Let's say I have some variables declared - but I don't know exactly which, I just have an array with variable names.
$variable_list = array('var1', 'var2', 'var3', 'var4');
We go ahead and assign some values.
foreach($variable_list as $var_name){
$$var_name = rand(100,1000);
}
Now I want to unset these variables in a similar fashion. Not remove them from list, but unset the ACTUAL variable.
foreach($variable_list as $var_name){
unset($var_name);
}
this does not work. any ideas?
foreach($variable_list as $var_name){
unset($$var_name);
}
PHP Manual
Why do you set them using variable variables ($$var_name) and don't unset them like that? This should work:
foreach($variable_list as $var_name){
unset($$var_name);
}
However, since you say:
Now I want to [...] not remove them from list, but unset the ACTUAL variable.
Simply use:
foreach($variable_list as $var_name){
$$var_name = null;
}
I would like to set a session variable with something akin to:
$key = '_SESSION[element]';
$$key = 'value';
This does indeed set $_SESSION['element'] equal to value, but it also seems to clear the rest of my $_SESSION variable, resulting in the $_SESSION array only containing the new key/value pair.
How can I write into the session using variable variables without nuking it?
Edit: if this can't be done, so be it, we'll probably have to restructure and do things the "right" way. I just wanted to know if there was an easy fix
#Mala, I think eval will help you.
Check the code below. It may help you for what you want.
session_start();
$_SESSION['user1'] = "User 1";
$_SESSION['user2'] = "User 2";
$key = "_SESSION['user3']";
eval("\$$key = 'User 3';");
foreach ($_SESSION as $key=>$value){
echo $key." => ".$value."<br/>";
unset($_SESSION[$key]);
}
session_destroy();
If you still have any trouble, Let me know. Thank you
From PHP Documentation:
Please note that variable variables cannot be used with PHP's
Superglobal arrays within functions or class methods. The variable
$this is also a special variable that cannot be referenced
dynamically.
How you ended up with a situation like this, is really questionable. You're probably doing something wrong.
EDIT
This little trick should give you what you want:
$key = '_SESSION[element]';
$key = str_replace(array('_SESSION[', ']'), '', $key);
$_SESSION[$key] = 'value';
var_dump($_SESSION);
This will basically produce the same results as xdazz's answer
Isn't this way better?
$key = 'element';
$_SESSION[$key] = 'value';
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.
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']);