2012-12-31 25 views
4

我是PHP新手(有點),我查了一下,找不到任何完全符合我的問題的信息,所以在這裏;設置表單作爲外部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> 

在這裏,您可以看到我已經嘗試設置這一行動功能「登錄()」,我已經在這個文件的頭部已經包含。

在外部的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"); 
} 

(忽略任何「你不應該這樣做,這樣做」,我只是在這裏畫一幅畫)。

所以基本上我想表單提交到特定的功能,這可能嗎?我在這裏做了一些根本性的錯誤嗎?

+0

是的,你不能這樣做那。它不會在響應正文中發送,並且只要它向您發送響應,就立即斷開與服務器的所有連接 – danronmoon

+0

您需要編寫登錄頁面並在表單操作中使用該頁面。獲取此頁面上的登錄信息,然後您可以從該登錄頁面調用登錄功能。 – Saleem

回答

3

正如其他人所說的,您不能自動將帖子定向到函數,但您可以動態地決定在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; 
    } 
} 
2

沒有提交表單的頁面,如果你在表單提交運行功能:

HTML:

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

PHP(的index.php):

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

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

表單上的動作是它提交表單的地方 - 即發送請求的頁面。正如你所說的,你的代碼是「位於頁面的頂部」,你需要將表單提交回它所在的頁面。所以,你既可以把頁面的完整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

相關問題