PHP $_POST 变量

Reading POST bodies, size limits, and choosing between GET and POST.

Beginner
Key Points`$_POST` is only populated for form content types.

Reading values

PHP
<?php
// 表单提交到本页,method="post"
$name = trim($_POST["fname"] ?? "");
$age  = trim($_POST["age"] ?? "");

if ($name === "" || $age === "") {
    echo "请填写完整";
} else {
    echo "欢迎 " . htmlspecialchars($name), "\n";
    echo "年龄 " . (int)$age, "\n";
}
Output
欢迎 Tom
年龄 18

$_POST is empty when...

Content-Type$_POSTRead with
application/x-www-form-urlencoded已填充$_POST
multipart/form-data已填充(文件进 $_FILES)$_POST
application/json空php://input + json_decode
text/plain空php://input

The most common trap with Vue/React frontends — $_POST stays empty for JSON bodies.

PHP
<?php
// 同时兼容表单和 JSON
$ctype = $_SERVER["CONTENT_TYPE"] ?? "";

if (str_contains($ctype, "application/json")) {
    $data = json_decode(file_get_contents("php://input"), true) ?? [];
} else {
    $data = $_POST;
}

echo "收到字段: " . implode(",", array_keys($data)), "\n";
echo "name = " . ($data["name"] ?? "-"), "\n";
Output
收到字段: name,age
name = Tom

Size limits

SettingDefaultEffect
post_max_size8M超过则 $_POST 整个变空
upload_max_filesize2M单个上传文件上限
max_input_vars1000超过则多余字段被丢弃
memory_limit128M处理大表单时可能先撞上
Exceeding post_max_size leaves $_POST and $_FILES empty with no error. Users see "please fill in everything" and nobody can find the cause. Check CONTENT_LENGTH on production.
PHP
<?php
$len = (int)($_SERVER["CONTENT_LENGTH"] ?? 0);
$max = 8 * 1024 * 1024;

if ($len > $max) {
    http_response_code(413);
    echo "请求体过大: " . round($len / 1048576, 1) . "MB\n";
    exit;
}

echo "大小正常: " . $len . " 字节\n";
Output
大小正常: 2048 字节

GET or POST

  • GET —— queries, paging, sorting, filters; shareable and bookmarkable
  • POST —— login, orders, mutations, uploads
  • PUT / DELETE —— REST APIs; PHP does not parse them, read php://input
  • Never GET a password —— it leaks to logs, history, Referer
PHP
<?php
// RESTful:从请求方法分发
$method = $_SERVER["REQUEST_METHOD"];

$body = [];
if (in_array($method, ["PUT", "PATCH", "DELETE"], true)) {
    $body = json_decode(file_get_contents("php://input"), true) ?? [];
}

echo "方法: $method\n";
echo "字段数: " . count($body) . "\n";
Output
方法: PUT
字段数: 2

Friends & Partners