簡體   English   中英

將表單操作設置為外部php文件中的函數

[英]setting form action as function in external php file

我是PHP新手(有點),我已經瀏覽了一下,找不到任何能夠滿足我的問題的信息,所以這里是;

假設我聲明了一個表單,包含2個字段和一個提交按鈕;

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

在這里你可以看到我試圖將動作設置為函數“logIn()”,我已經將其包含在此文件的標題中。

在外部php文件中,我有以下內容;

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

(忽略任何“你不應該這樣做,那樣做”,我只是在這里畫一幅畫)。

所以基本上我希望表單提交給特定功能,這可能嗎? 我在這里做了一些根本錯誤的事嗎?

正如其他人所說,你不能自動將帖子定向到一個函數,但你可以動態地決定在PHP端做什么,具體取決於使用PHP代碼提交的表單。 一種方法是使用隱藏輸入定義邏輯,以便您可以在同一頁面上處理不同的操作,如下所示:

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

然后在你的PHP中:

if (isset($_POST['action'])) {
    switch($_POST['action']) {
    case 'login':
        login();
        break;
    case 'otheraction':
        dosomethingelse();
        break;
    }
}

如果表單已提交,請不要​​將表單提交到頁面並運行您的函數:

HTML:

<form action="index.php" method="post">

PHP(index.php):

if ($_SERVER['REQUEST_METHOD'] == "POST"){
    // Run your function
    login();
}

要直接回答你的問題, 是的 ,你做錯了什么。 但是,它很容易修復。

表單上的操作是提交表單的位置 - 即發送請求的頁面。 正如您所說的那樣,您的代碼“位於頁面頂部”,您需要將表單提交回其所在的頁面。 因此,您可以將頁面的完整URL放在操作中,也可以將其留空:

<form name = "tryLogin" action = "" method = "post">

為了處理提交,PHP沒有辦法從客戶端代碼直接調用函數,但是,您可以通過發送帶有當前“任務”的隱藏字段以更多請求處理方式處理請求。

例如,在HTML表單中,嘗試添加:

<input type="hidden" name="task" value="logIn" />

然后,在PHP代碼中,嘗試添加以下內容:

if (isset($_POST['task'])) {
    if ($_POST['task'] == 'logIn') {
        // the user is trying to log in; call the logIn() function
        logIn();
    } else if ($_POST['task'] == 'logOut') {
        // the user is trying to log out; call the logOut() function
        logOut();
    }
}

此代碼將通過檢查task字段是否已過帳來檢查表單是否已提交。 然后,它將檢查值。 如果是logIn ,將logIn()函數。 或者,如果它是logOut ,則將logOut()函數。

要創建注銷表單,您可以相應地調整操作,並像上面那樣添加一個隱藏字段,但值為logOut

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM