开发者

PHP $_POST[$variable] in an included file, doesn't recognize the $variable and creates an error message

开发者 https://www.devze.com 2023-03-20 17:29 出处:网络
I would like to use \"dynamic\" $_POSTs, I don\'t know if I am using the right term but in other words I would like to use for example $_POST[$dynamic_variable] in a function that is in an included fi

I would like to use "dynamic" $_POSTs, I don't know if I am using the right term but in other words I would like to use for example $_POST[$dynamic_variable] in a function that is in an included file. Because the $dynamic_variable isn't recognized or because I can't use $_POST[something] in included files it doesn't work and I get an error message like Undefined variable: lastname in filename.php.

What is the safe to way to use $_POSTs in included files and when the $_POST[name] is variable?

Thank you!

///// updated - piece of code ///////

[code.php]

include("functions.php");

$test_arr = array(
"10开发者_高级运维|field_name1|500",
"20|field_name2|750",
...
);

checkForm($test_arr);

[functions.php]

function checkForm($test_arr) {
  foreach ($test_arr as $test) {
    $test_details = explode("|", $test);
    $field_name = $test_details[1];
    echo $_POST[$field_name];
  }
}


The $_POST array is available in all included PHP files. Normally, the $dynamic_variable is also available, if you do it like so:

$dynamic_variable = 'test';
include('include.php');

// in include.php: 
echo $_POST[$dynamic_variable];

But when declaring the $dynamic_variable inside a function or class, you don't have access to it outside. You could also declare it as global or hand it over as a parameter. Please also read the documentation about variable scope.


I would not write if it is smart to use globals like that or not.
Your problem is you tried to access a variable which does not exists, as the error message said.

To avoid the error message, you can do:

if(isset($_POST[$your_var_name]){
   //do something with $_POST[$your_var_name]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消