So, I'm trying to turn a variable into a function.
$go_menu=$_POST['menu'];
$go_menu();
Function potoato_chip()
{
echo "I like Doritos!";
}
Function apples()
{
echo "I like Fuji";
}
I am getting the data from the $go_menu=$_POST['menu']
but everything below $go_menu();
comes up blank.
The full code is here in a pastebin. Appreciate any help! I'm still learning!
You should not do this: it's highly insecure to execute a variable as a function when you just got that value from a POST! In particular because you're creating an admin interface. Any malicious person could execute other functions in your code if needed.
You should use if statements or a switch statement to control what needs to happen.
Note that Function
should be written as function
in PHP.
Make sure it's callable before calling it:
$go_menu = $_POST['menu'];
if(is_callable($go_menu))
$go_menu();
Keep an array of valid values; this will fix both your "no content" problem and your security problem:
$valid_actions = array('potato_chip', 'apples');
if(isset($_POST['menu']) && in_array($go_menu = $_POST['menu'], $valid_actions)) {
$go_menu();
}
First off, your code is incredibly insecure. Let's say I edit your form and submit a POST
request setting $_POST['menu']
to, let's say die
. This crashes your program. You can just imagine what else I can do with this. A correct way to do this would be with switch
:
switch $_POST['menu'] {
case "menu_1":
menu_1();
break;
case "menu_2":
menu_1();
break;
[...]
}
Generally speaking, I don't like to use variable variables or variable functions, because it's hard to keep track of the possible values of a variable. However, they can still be used if there are properly validated, like in minitech's answer. In your case though, since you seem to have a limited selection of functions that can be called, I would use switch
.