PHP: setting session variables through variable variables - php

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';

Related

Passing variable variables into if statement - php

I have a series of variables in php:
move1A = $row['column'];
move2A = $row['column'];
move3A = $row['column'];
etc.
I want to create a variable that will represent these variables and check if it is NULL. I have spent quite a bit of time looking, and although I believe that variable variables may be the key to my problem. So far I have tried:
$current_move_check = 'move'.$moveCounter.'A';
and
$current_move_check = '$move'.$moveCounter.'A';
Neither seem to work. Any suggestions for making something like this work? Thanks!
UPDATE:
So I'm trying to loop the moveXA variables based on user input and I need to run different script whether it is null or set.
I thought that:
elseif (!$$current_move_check) {
and
elseif ($$current_move_check) {
would work but they seem to not be outputting as expected.
Considering your update, I'd really suggest you to use an array, rather than the variable variables trick. Your code would makes more sense and be easier to maintain :
$count = 0;
$moveA[++$count] = $row['column'];
$moveA[++$count] = $row[...];
$moveA[++$count] = $row[...];
...
foreach ($moveA as $key => $value) {
if ($value) { // = $$current_move_check
} else { // = !$$current_move_check
}
}
As #MatsLindh pointed out in its comment : "Variable variables are never a good idea. Unless you know when it makes sense to break that rule, don't."
$current_move_check = 'move'.$moveCounter.'A';
echo $$current_move_check;
now you can check this as well like
if($$current_move_check!=NULL)
{
// do your code
}

Naming variables automatically from $_POST array.

My PHP script processes some POST variables.
Instead of manually naming each variable
$name = $_POST['name'];
$email = $_POST['account'];
I'd like my script to grab all the variable names from the $_POST array and automatically create variables with those names, e.g. (not code, just illustrating the principle)
foreach ($_POST as $name => $value) {
$[$name] = $value;
}
Is something like that possible?
You can use the extract function for this. But there is a risk, because you cannot know what data is posted, and it will create or overwrite variables in the scope in which you call it, possibly leading to unexpected behaviour.
You can partially counter this, using one of the flags for extract, for instance:
extract($_POST, EXTR_SKIP);
Anyway, make sure to read the two warnings (red block) on the documentation page of this function. And of course, the same warning applies when you do this using your own foreach loop, so answers suggesting that are no more secure.
There is extract function in php:
extract($_POST);
This is a very bad idea because it allows a user to create any variable in your PHP script (within the scope that it this code is used). Take for example if you have a $debugging flag:
$debugging = false;
foreach ($_POST as $name => $value) {
$$name = $value;
}
// some time later, we do a query and output the SQL if debugging
if($debugging){
echo $sql;
}
What if a malicious user submitted an input called debugging with a value of 1? Your debugging flag would be changed and the user could see sensitive debug data.
Try this (which is a bad practice):
foreach ($_POST as $name => $value) {
$$name = $value;
}
You can do this with variable variables as follows:
foreach ($_POST as $name => $value) {
$$name = $value;
}
You can also use the following format if you want to muck about with the variable names some more:
foreach ($_POST as $name => $value) {
${$name.'_1'} = $value;
}
There are comments here saying don't use variable variables - mainly because they are hard as heck to troubleshoot, make it damn hard for others to read your code and will (for the most part) create more headaches than they solve.

Checking variable is in URL then defining

I'm trying to do a simple function here, but it's not working.
I want to check if the variable is indeed in the URL, and if it is I want to define a variable with it.
if(isset($_GET['ref'])){
$ref = $_GET['ref'];
}
Could someone point out the errors?
It's probably that isset only checks if the variable has been declared. That variable could still be empty. so this will set $ref even when $_GET['ref'] = ""; Try this instead:
if(isset($_GET['ref'])){
if(!empty($_GET['ref'])))
{
$ref = $_GET['ref'];
}
}
The Get and Post variables are accessible to you as Arrays. I would loop over the array and treat it as a Key/Value pair. This will give you the ability to do what ever you would like with the key and the value.
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
See this previous Stack Overflow thread.
How do I get the key values from $_POST?

PHP Session variables from POST

I'm foreach-ing through my POST variables (though I'm using the $_REQUEST)
I want to put all the variables into their own Session variables, but it's simply not working.
Does this look incorrect to anyone?
<?php
foreach ($_REQUEST as $posted_name => $posted_value){
$_SESSION[$posted_name].' = '.$posted_value;
}
?>
I am including the session_start() in another part of my script. Above, of course.
There's a big problem with this:
$_SESSION[$posted_name].' = '.$posted_value;
You don't need to use the string concatenation . to set a session value. This line simple evaluates to a string and doesn't save anything in the $_SESSION superglobal.
Try this instead
<?php
session_start();
foreach ($_REQUEST as $key => $value){
$_SESSION[$key] = $value;
}
you didn't call this function yet:
session_start();
You intended to write this instead:
$_SESSION[$posted_name] = $posted_value;
Are you concatenating a string or are you setting a value?
Try
$_SESSION[$posted_name] = $posted_value;
and what #colighto said.
You'll need to session_start()
Your final code should look like
<?php
session_start();
foreach ($_POST as $posted_name => $posted_value) {
$_SESSION[$posted_name] = $posted_value;
//You added unnecessary commenting here
}
?>

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.

Categories