PHP - 表單驗證



術語“表單驗證”指的是確定使用者在各種表單元素中輸入的資料是否可以用於進一步處理的過程。在後續處理之前驗證資料可以避免可能的異常和執行時錯誤。

驗證可以在客戶端和伺服器端進行。當客戶端提交表單時,表單資料會被伺服器上執行的 PHP 指令碼攔截。使用 PHP 中提供的各種函式,可以完成伺服器端的表單驗證。

客戶端驗證

根據 HTML5 規範,新的輸入控制元件具有內建驗證功能。例如,型別為“email”的輸入元素,即使是文字欄位,也經過定製以接受符合電子郵件地址協議的字串。

驗證發生在資料提交到伺服器之前。對於其他輸入型別,如 URL、數字等,也是如此。

示例

下面是一個 HTML 表單,其中包含數字型別、電子郵件型別和 URL 型別的輸入元素。如果您輸入與所需格式不符的資料,則在嘗試提交表單時會顯示相應的錯誤訊息。

<h1>Input Validation</h1>
<form>
   <p><Label for "name">Enter your name</label>
   <input type = "text" id="name" name="name"></p>
   <p><label for="age">Enter age</label>
   <input type = "text" id = "age" name="age"></p>
   <p><label for="email">Enter your email:</label>
   <input type="text" id="email" name="email"></p>
   <p><label for="URL">Enter your website<label>
   <input type = "text" id="URL" name="url"></p>
   <input type="submit">
</form>

數字型別的文字欄位在右側顯示上下計數箭頭。只接受數字,並且可以遞增或遞減。

PHP Form Validation 1

如果電子郵件欄位中的資料無效,您會看到如下所示的錯誤訊息。

PHP Form Validation 2

類似地,URL 的任何不正確格式也會顯示如下所示的錯誤 -

PHP Form Validation 3

驗證函式

使用 PHP 進行伺服器端驗證的情況出現在表單資料透過客戶端驗證時,或者根本沒有客戶端驗證時。

在上例中使用的 HTML 表單中,讓我們刪除所有特殊輸入型別,並使用所有文字型別的文字欄位。表單使用 POST 方法提交到伺服器上的 hello.php。

<form action="hello.php" method="POST">
   <p><Label for "name">Enter your name</label>
   <input type = "text" id="name" name="name"></p>
   <p><label for="age">Enter age</label>
   <input type = "text" id = "age" name="age"></p>
   <p><label for="email">Enter your email:</label>
   <input type="text" id="email" name="email"></p>
   <p><label for="URL">Enter your website<label>
   <input type = "text" id="URL" name="url"></p>
   <input type="submit">
</form>

表單為空

如果使用者(可能是無意地)點選提交按鈕,您可以要求 PHP 再次顯示錶單。您需要檢查 $_POST 陣列是否已使用 isset() 函式初始化。如果沒有,header() 函式會將控制權重新定向回表單。

<?php 
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (isset($_POST)) {
         header("Location: hello.html", true, 301);  
         exit();  
      }
      // form processing if the form is not empty
   }
?>

示例

您還可以檢查在提交表單時是否有任何欄位為空。

<?php        
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      foreach($_POST as $k=>$v) {
         if (empty($v)==true) {
            echo "One or more fields are empty \n";
            echo "<a href = 'hello.html'>Click here to go back </a>";
            exit;
         }
         else
         echo "$k => $v \n";
      }
   }
?>

年齡欄位不是數字

在 HTML 表單中,名稱的輸入欄位為文字型別,因此它可以接受任何字元。但是,我們希望它為數字。這可以透過 is_numeric() 函式來確保。

<?php    
   if (is_numeric($_POST["age"])==false) {
      echo "Age cannot be non-numeric \n";
      echo "<a href = 'hello.html'>Click here to go back</a>";
   }
?>

PHP 還有 is_string() 函式來檢查欄位是否包含字串。另外兩個函式 trim() 和 htmlspecialchars() 也對錶單驗證很有用。

  • trim() - 從字串開頭和結尾刪除空白字元

  • htmlspecialchars() - 將特殊字元轉換為 HTML 實體,以防止跨站點指令碼 (XSS) 攻擊。

廣告