user1734974
user1734974

Reputation:

passing submit button name with variable?

I have a lot of files with different forms. All the forms are send to the same file, which, depending on what kind of name the submit button has, will include the right file to be used. Here is an example:

start.php:

<form name="input" action="controller.php" method="post">
    <input type="submit" name="dostuff1" value="SEND1" />
    <input type="submit" name="dostuff2" value="SEND2" />
</form>

controller.php:

if(isset($_POST['dostuff1'])) {
    $action = "dostuff1";

} elseif(isset($_POST['dostuff2'])) {
    $action = "dostuff2";
}

include($action.".php");

Now I'm looking for a way to throw out the whole "if else" part. What I want to know is if it's possible to send out a form with a button that has a variable stored in it's name, like this for example:

<input type="submit" name="action["dostuff1"]" value="SEND" />

Note: I'm still a noob (obviously) and the application I'm working on will be used solely for private purposes (security is not a concern here).

Upvotes: 1

Views: 1859

Answers (2)

Phil
Phil

Reputation: 164744

First...

<input type="submit" name="action["dostuff1"]" value="SEND" />

Lose the extra quotes

<input type="submit" name="action[dostuff1]" value="SEND">

Now, why not just have an array of key to filename mappings, for example

$incs = [
    'dostuff1' => 'dostuff1.php',
    'dostuff2' => 'dostuff2.php',
    // and so on
];

Then, you can check for the entry in that array, eg

if (isset($_POST['action']) && is_array($_POST['action'])) {
    $keys = array_keys($_POST['action']);
    $key = reset($keys);
    if (!array_key_exists($key, $incs)) {
        throw new UnexpectedValueException('Bad key');
    }

    include $incs[$key];
}

Upvotes: 3

tckmn
tckmn

Reputation: 59273

You could use array_keys:

include(array_keys($_POST)[0] . ".php");

Now, obviously, this would be a terrible idea for security, but you did say that:

the application I'm working on will be used solely for private purposes (security is not a concern here)

A better idea for security (and in general) would be:

$files = array("dostuff1", "dostuff2");
foreach ($files as &$file) {
    if (isset($_POST[$file])) {
        include($file . ".php");
        break;
    }
}
unset($file);

Upvotes: 1

Related Questions