Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting form action as function in external php file

Tags:

html

forms

php

I'm new to PHP (somewhat), and i've had a look around and can't find any information which caters exactly to my questions, so here it is;

Let's say i declare a form, with 2 fields and a submit button;

<form name = "tryLogin" action = "logIn()" method = "post">
            Username: <input type = "text" name = "username" placeholder = "username.."><br>
            Password: <input type = "text" name = "password" placeholder = "password.."><br>
            <input type = "submit" value = "Submit">
</form>

Here you can see i've tried to set the action as a function "logIn()", which i've included already in the header of this file.

In an external php file i've got the following;

function logIn()
{
if($_POST['username'] == "shane" && $_POST['password'] == "shane")
{
    $_SESSION['loggedIn'] = '1';
    $_SESSION['user'] = $_POST['username'];
}

header ("Location: /index.php");
}

function logOut()
{
$_SESSION['loggedIn'] = '0';
header ("Location: /index.php");
}

(Ignore any "y'shouldn't do this, do that", i'm just painting a picture here).

So basically i want the form to submit to that particular function, is that possible? Am i doing something fundamentally wrong here?

like image 349
Kestami Avatar asked Dec 31 '12 02:12

Kestami


1 Answers

As others have said, you can't direct a post to a function automatically, but you can dynamically decide what to do on the PHP side depending on which form is submitted with PHP code. One way is to define your logic with a hidden input so you can handle different actions on the same page, like this:

<form name="tryLogin" action="index.php" method="post">
            <input type="hidden" name="action" value="login" />
            Username: <input type="text" name="username" placeholder="username.."><br />
            Password: <input type="text" name="password" placeholder="password.."><br />
            <input type="submit" value="Submit">
</form>

<form name="otherform" action="index.php" method="post">
            <input type="hidden" name="action" value="otheraction" />
            Type something: <input type="text" name="something"><br />
            <input type="submit" value="Submit">
</form>

and then in your PHP:

if (isset($_POST['action'])) {
    switch($_POST['action']) {
    case 'login':
        login();
        break;
    case 'otheraction':
        dosomethingelse();
        break;
    }
}
like image 127
Levi Avatar answered Oct 21 '22 14:10

Levi