KeirDavis
KeirDavis

Reputation: 665

Multiple forms which both go to PHP_SELF

I have two forms on 1 page, how would I go about working out in PHP which forms was used?

Form 1:

<form name="loginform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <input type="text" name="vuser" placeholder="Email"><br/>
    <input type="password" name="vpass" placeholder="Password"><br/>
    <input type="submit" name="submit" value="Log in">
</form>

Form 2:

<form name="otherform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <input type="text" name="newu" placeholder="Email"><br/>
    <input type="password" name="newp" placeholder="Password"><br/>
    <input type="submit" name="submit" value="New Formsss">
</form>

Then, my PHP code has this, but I'm not too sure how I would do it.

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    //if otherform was submitted do this:
        //echo "Otherform";
    //else if loginform was submitted do this:
        //echo "Loginform";
    die;
}

Upvotes: 2

Views: 1929

Answers (2)

user3788685
user3788685

Reputation: 3103

I was able to just use separate name for the submit buttons and catch which one was used;

if(isset($_POST['submit-a'])){
        $vuser= $_POST['vuser'];
        exec("external script $vuser");
    };

if(isset($_POST['submit-b'])){
        $newu= $_POST['newu'];
        exec("external script $newu");
    };

Andd the button code is;

<button type="submit" name="submit-a" class="btn btn-primary">Submit</button>
<button type="submit" name="submit-b" class="btn btn-primary">Submit</button>

In my case I'm grabbing the vars to pass to an external script.

Upvotes: 0

user399666
user399666

Reputation: 19879

You could add two hidden fields called action to each one of your forms:

<input type="hidden" name="action" value="login">

and in the other:

<input type="hidden" name="action" value="other">

Then, with PHP:

$action = isset($_POST['action']) ? $_POST['action'] : null;

switch($action){
    case 'other':
        //process
        break;
    case 'login':
        //process
        break;
    default:
        //action not found
        break;
}

Upvotes: 4

Related Questions