PHP 超级全局变量

Nine built-in arrays available in every scope.

Beginner
Key PointsSuperglobals are accessible inside functions without a `global` declaration.

九个超级全局变量

VariableContentsTypical use
$GLOBALS所有全局变量在函数里改全局变量
$_SERVER服务器与请求信息请求方法、URL、IP
$_GETURL 查询串参数分页、筛选、搜索
$_POST表单 POST 体提交表单、上传元数据
$_FILES上传文件信息文件上传
$_COOKIE客户端 Cookie记住登录、偏好
$_SESSION服务端会话登录状态、购物车
$_REQUESTGET + POST + COOKIE 合并不建议使用
$_ENV环境变量配置注入
$_REQUEST's sources depend on the request_order ini setting — unpredictable and risky. Use the specific array.

$_GET 与 $_POST

Requesting http://localhost/info.php?name=Tom&age=18:

PHP
<?php
echo $_GET['name'] ?? '匿名', "\n";
echo $_GET['age'] ?? '-', "\n";
echo $_SERVER['REQUEST_METHOD'], "\n";
echo $_SERVER['QUERY_STRING'], "\n";
echo $_SERVER['SCRIPT_NAME'], "\n";
Output
Tom
18
GET
name=Tom&age=18
/info.php

On form submission:

PHP
<?php
// 表单: <form method="post"><input name="user"><input name="pwd" type="password"></form>
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = trim($_POST['user'] ?? '');
    $pwd  = $_POST['pwd'] ?? '';

    if ($user === '' || $pwd === '') {
        echo "请填写完整\n";
    } else {
        echo "收到用户: " . htmlspecialchars($user), "\n";
        echo "密码长度: " . strlen($pwd), "\n";
    }
} else {
    echo "请用 POST 提交\n";
}
Output
收到用户: Tom
密码长度: 8
**Never interpolate $_GET / $_POST into SQL or HTML.** Escape output with htmlspecialchars(), use prepared statements for the database.

$GLOBALS

PHP
<?php
$x = 1;

function inc() {
    $GLOBALS['x']++;
}

inc();
inc();
echo $x, "\n";
Output
3

global $x; is the equivalent per-variable form. Better still: avoid globals and pass dependencies as arguments.

$_SERVER 常用键

KeyValue
REQUEST_METHODGET / POST / PUT / DELETE
REQUEST_URI含查询串的完整路径
SCRIPT_NAME当前脚本路径
HTTP_HOST请求的域名
REMOTE_ADDR客户端 IP
HTTP_USER_AGENT浏览器标识(可伪造)
HTTPS非空表示走 HTTPS
CONTENT_TYPE请求体类型,如 application/json

REMOTE_ADDR is the direct peer address — the proxy's IP behind one. X-Forwarded-For carries the real client but can be forged; trust it only behind a trusted proxy.

JSON bodies are not in $_POST

For Content-Type: application/json PHP does not populate $_POST. Read the raw input stream yourself.

PHP
<?php
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo "非法 JSON\n";
    exit;
}

echo "收到字段: " . implode(",", array_keys($data)), "\n";
Output
收到字段: name,age

php://input can be read repeatedly (5.6+), whereas the raw body is consumed once $_POST is parsed. This is the standard pattern for APIs.

Friends & Partners