Unable to create Dynamic Variables - php

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

Related

Is it possible to put a php variable inside $_POST['']?

I was wondering if it's possible to put a PHP variable inside $_POST[''] like this:
$_POST[$variable];
I'm asking this because I have a page in which all the inputs have dynamic names according to how many orders the user has made and when I must retrieve their values through post, I never know the names but if I would have something like $_POST[$variable] I would know. The variable is a string and so it would turn out like $_POST['String'].
So is it possible to do something like this?
$numero = $count_ficha;
$countU = 1;
for ($i = 1;$i < $numero + 1;$i++) {
$identificador = "identificadorNI".$countU;
$identificador2 = "identificador".$countU;
$id_subencomenda = $_POST[$identificador];
$countU++;
echo $id_subencomenda;
}
Yes, it is possible to use a variable inside $_POST[''] such as $_POST[$variable]
You will still be required, however, to define a value for $variable
It is posible, but if you don't know the key of $POST[] that you're trying to get the value of, how could you know what value that you have to put on $variable?
For unknow values, the best you can do is a foreach, so you can iterate all the $POST array and then you can do whatever you want with the values, like this
foreach ($_POST as $key) {
//do whatever you want with the $key
}
Check PHP foreach
if you have a dynamic value for the page you just use some $variable because $_POST is use to send information from some HTTP POST method.
(http://php.net/manual/en/reserved.variables.post.php)
maybe you can resolve your problem by creating a global variable.

PHP How do I read the form variables with empty square brackets in their name

In my php file when I submit I'm able to read the following variables quite easily (see attached picture)
$mobile = $_REQUEST['mobile'];
$about = $_REQUEST['about'];
$comment = $_REQUEST['comment'];
Now my question is.. how do I read the "category[]" form value?
Just read it like you read normal variables.
$category = $_REQUEST['category'];
Unlike other variables it will return you PHP Array. You can iterate over this variable just like normal PHP Array.
foreach($category as $cat) {
echo $cat;
}
Make sure your check if request actually have the value you're looking for by using isset(). Otherwise above code might throw undefined indexed error.
You should try
foreach ($_REQUEST['category'] as $category) {
var_dump($category);
}
Get array variable
$categories = $_REQUEST['category'];
var_dump($categories);
Try this, this'll also show you the index or keys if you need
print_r ($_REQUEST['category']);

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.
}

Yii - Manipulating a sesssion variable

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

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