PHP

PHP 讀取 POST 表單資料教學與範例

介紹如何使用 PHP 讀取以 POST 方法傳送的網頁表單資料。

POST 網頁表單

以下是簡單的網頁表單,若要採用 POST 方法來傳遞資料,可在 <form> 中加上 method="post",而傳送的目的網址則可用 action 指定:

<!DOCTYPE html>
<html>
<head>
  <title>POST</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2>測試表單</h2>
<form method="post" action="action.php">
  <input type="text" name="username" placeholder="Enter Username" />
  <input type="password" name="password" placeholder="Enter Password" />
  <input type="submit" name="submit-btn" value="submit" />
</form>
</body>
</html>

這張表單在按下 submit 按鈕之後,會以 POST 的方式將資料送至 action.php

PHP 接收 POST 資料

在 PHP 中我們可以透過 $_POST 變數來取得以 POST 方式所傳送的資料,典型的用來接收 POST 表單資料的 action.php 內容如下:

<?php
if (isset($_POST["submit-btn"])) {
  # 依欄位名稱取得資料
  print("<div>Username:" . $_POST['username'] . "</div>");
  print("<div>Password:" . $_POST['password'] . "</div>");

  # 輸出所有欄位資料(除錯用)
  echo "<pre>";
  print_r($_POST);
  echo "</pre>";
}
?>

收到 POST 表單資料之後,輸出會類似這樣:

Username:abc
Password:1234
Array
(
    [username] => abc
    [password] => 1234
    [submit-btn] => submit
)

這裡的 print_r 函數會將 $_POST 陣列的所有內容列出,在開發與除錯階段非常好用,而除了 print_r 函數之外,亦可使用 var_dump 函數。

PHP 讀取輸入串流資料

除了以常用的 $_POST 變數取得 POST 表單資料之外,亦可透過 PHP 的 php://input 這個輸入的串流來取得原始的資料:

<?php
if (isset($_POST["submit-btn"])) {
  # 從 PHP 輸入串流讀取原始資料
  $post_data = file_get_contents('php://input');
  echo "<div>" . $post_data . "</div>";
}
?>

從 PHP 的 php://input 輸入串流取得的資料會類似這樣:

username=abc&password=1234&submit-btn=submit

參考資料

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago