Put all parameters from a session into variables - php

I have the following code:
if(isset($_SESSION["spgrund"])) {
$spgrund = $_SESSION["spgrund"];
}else{
$spgrund = '';
}
This code is repeated about 20 times for each session variable. How can I make a loop out of it?
foreach($_SESSION as $key => $value){
$$key = $value;
}
I think that should work. But I get undefined variable error messages. Can't I use such a loop?

What you actually try to achieve is already available in PHP, the extract­Docs function:
extract($_SESSION);
From it's documentation:
Import variables from an array into the current symbol table.
Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.
You would still need look for undefined variables however. Probably you should define them first?

foreach($_SESSION as $key => $value)
{
$$key = $value;
}
you missed the $ for value

Related

Create php variable from HTML post name and value

I have a large HTML form posting many fields to a PHP page. I'm assigning all those fields to PHP variables one by one. Is there a way to put to create a function to auto assign the POST value to a PHP variable?
This is my code now:
if (!empty($_POST["x"])) {
$x = clean_post($_POST["x"]); }
if (!empty($_POST["y"])) {
$y = clean_post($_POST["y"]);
}?>
Thanks!
You can do this using the array_keys() function and a foreach-loop like this:
foreach (array_keys($_POST) as $key) {
${$key} = $_POST[$key];
}
But why not use the $_POST array in the first place?
Yes, but it's a rubbish idea. They actually had this in PHP, but removed it. It was called register_globals. So for instance, $_POST['name'] would automatically have $name created.
If you insist on this terrible idea, you should be able to do it like this:
foreach ($_POST as $key => $value) {
$$key = $value;
}
Don't do it though! Read this for more info https://secure.php.net/manual/en/security.globals.php

Unable to define variables as empty in foreach loop

I'm trying to define three empty variables through a foreach loop to make my code cleaner. This is what I've tried, however I see the error:
Notice: Undefined variable: hi
foreach(['$hi','$bye','$hello'] as $key) {
$key = "";
}
$hi .= "hello";
When I remove the foreach loop and simply define each empty variable one by one, like this, it works:
$hi = "";
$bye = "";
$hello = "";
You're assigning to $key, not to the variable that's named by it. To indirect through a variable, you need to use $$key. But the value of the variable shouldn't include the $, just the variable name.
foreach (['hi', 'bye', 'hello'] as $key) {
$$key = "";
}
$hi .= "hello";
However, if you ever find yourself using variable variables like this, you're almost certainly doing something wrong. You should probably be using an associative array instead.
You have strings which are saved in $key. So the value of $key is a string and you set it to "".
Later you want to append something to a variable you never used.
Try to remove the ' and write
foreach([$hi, $bye, $hello] as $key) {
Generally thats not the best way to initialise multiple variables. Try this
Initializing Multiple PHP Variables Simultaneously
Easier way:
list($hi, $bye, $hello) = "";
foreach creates a new array variable in memory, so you only clear these values inside the array in memory which is useless out of the foreach sentence. the best way is:
$h1=$bye=$hello="";
I didn't think that a foreach process will work more fast than a Simple equal (=), foreach function uses more CPU resources than a simple =. That's because the math CPU exists.

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.

Process form fields with foreach loop on posting form?

I'm posting 20 results from a form, to be used on the next page, is there a quick foreach way of posting:
$UserID1 = $_POST['UserID1'];
Where the ID changes each time rather than listing it 20 odd times? I thought a foreach statement, but i'm not too sure where to begin with it?
You can use extract():
extract($_POST);
echo $UserID1; // This now works
This is not considered a good programming practice but will do what you want.
The other answers will do the job just fine, however they introduce security issues.
Code such as:
foreach($_POST as $key => $value){
$$key = $value; //Assign the value to a variable named after $key
}
Allows me to post any form field I wish to your page and alter any variables value, for example, say you have code something like this elsewhere:
if ($validation) { // Do something }
Then I am able to post a form field named validation with a value of 1 and manipulate your code as that would assign a variable called $validation to a value of my choosing.
Using that code to assign variables from all your $_POST values automatically, is the same as using register_globals which was deprecated due to it's blatent security issues. See: http://www.php.net/manual/en/security.globals.php
If you must do this, you must check that the posted values are something that you expect. For example, check for the existance of UserID. This will only allow the creation of variables if they begin with UserID:
foreach($_POST as $key => $value) {
if (substr($key, 0, 6) == 'UserID') {
$$key = $value; //Assign the value to a variable named after $key
}
}
This will check for $_POST['UserID1'] and create $UserID1 and $_POST['UserID2'] and create $UserID2...
foreach($_POST as $key => $value){
$$key = $value; //Assign the value to a variable named after $key
}

PHP: setting session variables through variable variables

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

Categories