PHP 表单

How an HTML form hands data to PHP, and the minimal handling loop.

Beginner
Key PointsA field's `name` becomes the array key; the form's `method` decides `$_GET` or `$_POST`.

A minimal form

The form page is plain HTML; another PHP script receives the submission. action names the receiver, method picks get or post.

HTML
<form action="welcome.php" method="post">
    名字: <input type="text" name="fname"><br>
    年龄: <input type="text" name="age"><br>
    <input type="submit" value="提交">
</form>

The receiver reads $_POST by name. Check existence first, or a direct visit to welcome.php raises an undefined index warning.

PHP
<?php
$name = $_POST["fname"] ?? "";
$age  = $_POST["age"] ?? "";

if ($name === "" || $age === "") {
    echo "请通过表单提交";
    exit;
}

echo "欢迎 " . htmlspecialchars($name) . "<br>";
echo "你的年龄是 " . htmlspecialchars($age) . " 岁。";
Output
欢迎 Tom<br>你的年龄是 18 岁。

GET vs POST

AspectGETPOST
Where the data goesURL 查询串请求体
Visible in URL是否
Length limit受 URL 长度限制(约 2KB)受 post_max_size 限制
Bookmarkable可以不可以
Idempotent是,刷新安全否,刷新会重复提交
Use for查询、分页、筛选登录、上传、写操作
Never send passwords over GET. Query strings land in history, access logs and Referer headers. Write operations should not use GET either.

Field types

InputPHP receives
<input type="text">字符串
<input type="checkbox">勾选才有键;多选加 name="x[]" 得数组
<input type="radio">字符串,单个值
<select multiple>数组
<textarea>字符串(含换行)
<input type="file">进 $_FILES,不进 $_POST
PHP
<?php
// 表单: <input type="checkbox" name="hobby[]" value="read">
$hobbies = $_POST["hobby"] ?? [];
echo is_array($hobbies) ? implode(",", $hobbies) : $hobbies, "\n";
echo count($hobbies), "\n";
Output
read,music
2

Self-submitting forms

Leave action empty so the form posts to itself — the page both renders and handles. The classic PHP utility pattern.

PHP
<?php
$submitted = ($_SERVER["REQUEST_METHOD"] ?? "") === "POST";
$msg = "";

if ($submitted) {
    $n = (int)($_POST["n"] ?? 0);
    $msg = "你输入了 $n,平方是 " . ($n * $n);
}

echo $submitted ? "<p>$msg</p>" : '<form method="post"><input name="n"></form>', "\n";
Output
<p>你输入了 7,平方是 49</p>
Refreshing a self-posting form resubmits. Redirect after handling — the Post/Redirect/Get pattern.

The standard handling pattern

  1. Check that the request method is POST
  2. Read $_POST with ?? defaults
  3. trim() the input
  4. Validate type and range, collect errors
  5. Re-render with errors, or process
  6. Redirect after processing

The following chapters unpack each step, then assemble them in the complete form example.

Friends & Partners