<?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";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、PHP 8.4 本地 CLI 环境。
入口文件:projects/php-file-upload-lab/explore-file-upload.php
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-file-upload.php,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1244.zip