蓝色天空.知识 · 实践 · 创造
我的收藏
PHP 教程目录 95章
课程介绍
PHP / LEARN BY DOING

PHP 文件上传

核对 multipart/form-data 上传表单结构、$_FILES 五项元数据与错误码、基于扩展名/大小及 fileinfo 真实 MIME 的安全拦截,以及上传目录保存与防覆盖流程。

学完这一章,你能够

  • 核对 multipart/form-data 上传表单结构、$_FILES 五项元数据与错误码、基于扩展名/大小及 fileinfo 真实 MIME 的安全拦截,以及上传目录保存与防覆盖流程。

上传项目结构与 HTML 表单配置

PHP 文件上传工程通常包含上传表单(`form.html`)、接收脚本(`upload_file.php`)与持久化存储目录(`upload/`);原参考页面的外部示范压缩包因来源站点保持停止访问未向原站抓取,已登记于附件清单并以本站离线 PHP 8.4 实验完整替代核验。HTML 表单必须设置 `method="post"` 与 `enctype="multipart/form-data"` 以支持二进制分块传输,并放置 `<input type="file" name="file">` 控件。允许外部上传属于高危入口,必须限制权限、后缀、真实内容类型与文件大小。

$_FILES 元数据与上传安全限制

服务端通过全局二维数组 `$_FILES['file']` 读取上传元数据,包含五个核心键:`name`(客户端原始文件名)、`type`(浏览器声明的 MIME 类型)、`size`(字节大小)、`tmp_name`(服务端临时副本路径)与 `error`(上传错误码,`UPLOAD_ERR_OK` 为 `0`)。本站 PHP 8.4.27 实测核对全部五项键名、`15360` 字节换算为 `15 kB` 以及 `UPLOAD_ERR_OK(0)` 至 `UPLOAD_ERR_CANT_WRITE(7)` 标准常量值。

仅校验客户端提供的 `$_FILES['file']['type']` 容易被伪造;更可靠的做法是将允许扩展名白名单(`gif`、`jpeg`、`jpg`、`png`)、大小上限(`< 204800` 字节即 200 kB)与服务端 `finfo(FILEINFO_MIME_TYPE)` 魔数内容检测结合。本站使用本地 `gd` 实时生成真 PNG 与伪装为 `.png` 的 PHP 脚本文本以及 210 kB 超大文件实测:`finfo` 识别真 PNG 为 `image/png` 放行,识别伪装脚本为 `text/x-php` 立即拦截,同时拦截超 200 kB 文件。

持久化保存临时上传文件

PHP 在请求结束后会自动清除 `tmp_name` 临时副本,因此通过校验的文件需检查目标目录是否已存在同名文件(`file_exists()`),并在 Web SAPI 环境下调用 `move_uploaded_file()`(同时以 `basename()` 或随机文件名阻断 `../` 路径穿越)持久化到 `upload/` 目录,生产环境还应避免授予目录 `777` 全局可写权限并禁用上传目录脚本执行。本站离线 CLI 实测 `basename('../../evil/avatar.png')` 净化为 `avatar.png`、`is_uploaded_file()` 在非 HTTP POST SAPI 下按预期返回 `false`、首次保存后 SHA-256 校验一致且二次检测准确捕获重名冲突。

运行上传表单元数据、finfo 真实 MIME 拦截、安全存储与错误码常量实验

含完整源码 · 174 行
展开查看收起
php
<?php
declare(strict_types=1);

$tmpDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php_upload_lab_' . bin2hex(random_bytes(6));
$uploadDir = $tmpDir . DIRECTORY_SEPARATOR . 'upload';
mkdir($uploadDir, 0777, true);

$cleanup = static function (string $dir) use (&$cleanup): void {
    if (!is_dir($dir)) {
        return;
    }
    foreach (scandir($dir) ?: [] as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $path = $dir . DIRECTORY_SEPARATOR . $item;
        if (is_dir($path)) {
            $cleanup($path);
        } else {
            @unlink($path);
        }
    }
    @rmdir($dir);
};

$cases = [];

try {
    // Case 1: Multipart form requirements and $_FILES 5 standard metadata keys
    $formHtml = '<form action="upload_file.php" method="post" enctype="multipart/form-data"><input type="file" name="file" id="file"></form>';
    $mockFiles = [
        'file' => [
            'name' => 'avatar.png',
            'type' => 'image/png',
            'size' => 15360,
            'tmp_name' => $tmpDir . '/phpTMP01',
            'error' => UPLOAD_ERR_OK,
        ],
    ];
    $actual1 = [
        'has_multipart_enctype' => str_contains($formHtml, 'enctype="multipart/form-data"'),
        'has_file_input' => str_contains($formHtml, 'type="file"'),
        'files_keys' => array_keys($mockFiles['file']),
        'size_kb' => $mockFiles['file']['size'] / 1024,
        'error_ok' => $mockFiles['file']['error'] === 0,
    ];
    $expected1 = [
        'has_multipart_enctype' => true,
        'has_file_input' => true,
        'files_keys' => ['name', 'type', 'size', 'tmp_name', 'error'],
        'size_kb' => 15,
        'error_ok' => true,
    ];
    $cases[] = [
        'name' => 'upload_form_multipart_and_files_meta',
        'passed' => $actual1 === $expected1,
        'expected' => $expected1,
        'actual' => $actual1,
    ];

    // Case 2: Real finfo MIME detection + extension whitelist + 200 kB size limit
    $realPng = $tmpDir . '/real.png';
    $img = imagecreatetruecolor(8, 8);
    imagepng($img, $realPng);
    imagedestroy($img);

    $fakePng = $tmpDir . '/shell.png';
    file_put_contents($fakePng, "<?php echo 'not a png'; ?>\n");

    $oversizedPng = $tmpDir . '/huge.png';
    file_put_contents($oversizedPng, file_get_contents($realPng) . str_repeat("\0", 210000));

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $allowedExts = ['gif', 'jpeg', 'jpg', 'png'];
    $allowedMimes = ['image/gif', 'image/jpeg', 'image/png'];
    $maxBytes = 204800; // 200 kB

    $validateUpload = static function (string $origName, string $tmpPath) use ($finfo, $allowedExts, $allowedMimes, $maxBytes): array {
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        $size = filesize($tmpPath);
        $realMime = (string)$finfo->file($tmpPath);
        $okExt = in_array($ext, $allowedExts, true);
        $okMime = in_array($realMime, $allowedMimes, true);
        $okSize = ($size !== false && $size < $maxBytes);
        return [
            'ext' => $ext,
            'real_mime' => $realMime,
            'under_200kb' => $okSize,
            'accepted' => ($okExt && $okMime && $okSize),
        ];
    };

    $actual2 = [
        'valid_png' => $validateUpload('photo.PNG', $realPng),
        'disguised_php' => $validateUpload('shell.png', $fakePng),
        'oversized_png' => $validateUpload('huge.png', $oversizedPng),
    ];
    $expected2 = [
        'valid_png' => ['ext' => 'png', 'real_mime' => 'image/png', 'under_200kb' => true, 'accepted' => true],
        'disguised_php' => ['ext' => 'png', 'real_mime' => 'text/x-php', 'under_200kb' => true, 'accepted' => false],
        'oversized_png' => ['ext' => 'png', 'real_mime' => 'image/png', 'under_200kb' => false, 'accepted' => false],
    ];
    $cases[] = [
        'name' => 'finfo_mime_and_extension_validation',
        'passed' => $actual2 === $expected2,
        'expected' => $expected2,
        'actual' => $actual2,
    ];

    // Case 3: Saving uploaded file with basename sanitization, duplicate check, and is_uploaded_file CLI boundary
    $incomingName = '../../evil/avatar.png';
    $safeName = basename($incomingName);
    $targetPath = $uploadDir . DIRECTORY_SEPARATOR . $safeName;

    $isUploadedCli = is_uploaded_file($realPng); // false in CLI because not an HTTP POST SAPI upload
    $firstExists = file_exists($targetPath);
    $copied = copy($realPng, $targetPath);
    $secondExists = file_exists($targetPath);
    $sameContent = (hash_file('sha256', $realPng) === hash_file('sha256', $targetPath));

    $actual3 = [
        'sanitized_basename' => $safeName,
        'is_uploaded_file_in_cli' => $isUploadedCli,
        'existed_before_save' => $firstExists,
        'saved_ok' => $copied,
        'duplicate_detected_second_try' => $secondExists,
        'hash_matches' => $sameContent,
    ];
    $expected3 = [
        'sanitized_basename' => 'avatar.png',
        'is_uploaded_file_in_cli' => false,
        'existed_before_save' => false,
        'saved_ok' => true,
        'duplicate_detected_second_try' => true,
        'hash_matches' => true,
    ];
    $cases[] = [
        'name' => 'safe_store_and_duplicate_check',
        'passed' => $actual3 === $expected3,
        'expected' => $expected3,
        'actual' => $actual3,
    ];

    // Case 4: Standard PHP UPLOAD_ERR_* status constants
    $actual4 = [
        'UPLOAD_ERR_OK' => UPLOAD_ERR_OK,
        'UPLOAD_ERR_INI_SIZE' => UPLOAD_ERR_INI_SIZE,
        'UPLOAD_ERR_FORM_SIZE' => UPLOAD_ERR_FORM_SIZE,
        'UPLOAD_ERR_PARTIAL' => UPLOAD_ERR_PARTIAL,
        'UPLOAD_ERR_NO_FILE' => UPLOAD_ERR_NO_FILE,
        'UPLOAD_ERR_NO_TMP_DIR' => UPLOAD_ERR_NO_TMP_DIR,
        'UPLOAD_ERR_CANT_WRITE' => UPLOAD_ERR_CANT_WRITE,
    ];
    $expected4 = [
        'UPLOAD_ERR_OK' => 0,
        'UPLOAD_ERR_INI_SIZE' => 1,
        'UPLOAD_ERR_FORM_SIZE' => 2,
        'UPLOAD_ERR_PARTIAL' => 3,
        'UPLOAD_ERR_NO_FILE' => 4,
        'UPLOAD_ERR_NO_TMP_DIR' => 6,
        'UPLOAD_ERR_CANT_WRITE' => 7,
    ];
    $cases[] = [
        'name' => 'upload_error_codes_mapping',
        'passed' => $actual4 === $expected4,
        'expected' => $expected4,
        'actual' => $actual4,
    ];
} finally {
    $cleanup($tmpDir);
}

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
核对 $_FILES 五键与错误常量、gd 真 PNG 通过而伪装 PHP 脚本(text/x-php)与 >200kB 文件被 finfo 拦截、basename 净化与重名检测。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1232.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1244.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

HTTP 请求中的文件名与 Content-Type 均由客户端提交,攻击者可将恶意 PHP 脚本改名为 .png 并伪造 image/png 头;服务端必须使用 finfo(FILEINFO_MIME_TYPE) 检查文件真实魔数内容,并对保存路径做 basename/随机重命名与禁止脚本执行。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习