1

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

2
  • Have you tried doing that? It is faster to try and see for yourself than to come on here and wait for a response. Commented Dec 22, 2013 at 23:54
  • Why? What's it you don't like about the way you're doing it? Commented Dec 23, 2013 at 0:56

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

@user574632 Why? "the application I'm working on will be used solely for private purposes (security is not a concern here)" from the question
just bad practice, other people will read and perhaps use this code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.