$max_size) { $file['error'] = '文件大小不能超过50MB'; return $file; } // 允许的文件类型:图片格式和PDF $allowed_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml', 'application/pdf' ); // 明确禁止的文件类型(包含PHP木马常用类型) $forbidden_types = array( 'application/zip', 'application/x-zip-compressed', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/x-tar', 'application/gzip', 'application/x-executable', 'application/x-msdownload', 'text/x-php', 'application/x-php', 'text/php', 'application/php', 'text/x-script.php', 'application/x-httpd-php', 'application/x-httpd-php-source', 'text/html', 'text/javascript', 'application/javascript', 'text/x-shellscript' ); // 检查是否为禁止的文件类型 if (in_array($file['type'], $forbidden_types)) { $file['error'] = '出于安全考虑,不允许上传此类型的文件'; return $file; } // 获取文件信息 $file_info = pathinfo($file['name']); $filename = strtolower($file['name']); $extension = isset($file_info['extension']) ? strtolower($file_info['extension']) : ''; // PHP木马防护:检查双重扩展名 if (preg_match('/\.(php|phtml|php3|php4|php5|php7|phps|pht|phar)\./i', $filename)) { $file['error'] = '检测到可疑的双重扩展名,上传被拒绝'; return $file; } // 扩展的危险扩展名列表(包含PHP木马常用扩展名) $forbidden_extensions = array( 'zip', 'rar', '7z', 'tar', 'gz', 'exe', 'bat', 'cmd', 'com', 'scr', 'msi', 'php', 'php3', 'php4', 'php5', 'php7', 'phtml', 'phps', 'pht', 'phar', 'js', 'html', 'htm', 'xhtml', 'shtml', 'jsp', 'asp', 'aspx', 'pl', 'py', 'rb', 'sh', 'bash', 'cgi', 'htaccess', 'htpasswd' ); if (in_array($extension, $forbidden_extensions)) { $file['error'] = '不允许上传 .' . $extension . ' 格式的文件'; return $file; } // PHP木马防护:检查可疑文件名模式 $suspicious_patterns = array( '/shell/i', '/webshell/i', '/backdoor/i', '/trojan/i', '/hack/i', '/exploit/i', '/bypass/i', '/upload/i', '/cmd/i', '/eval/i', '/base64/i', '/decode/i', '/phpinfo/i', '/system/i', '/exec/i' ); if (is_array($suspicious_patterns) && !empty($suspicious_patterns)) { foreach ($suspicious_patterns as $pattern) { if (preg_match($pattern, $filename)) { $file['error'] = '检测到可疑文件名,上传被拒绝'; return $file; } } } // 检查是否为允许的文件类型 if (!in_array($file['type'], $allowed_types)) { $file['error'] = '只允许上传图片文件(JPEG, PNG, GIF, WebP, SVG)和PDF文档'; return $file; } // PHP木马防护:文件内容检查(针对图片文件) if (strpos($file['type'], 'image/') === 0 && $file['tmp_name']) { $content_check = nenghui_check_file_content($file['tmp_name']); if (!$content_check['safe']) { $file['error'] = $content_check['message']; return $file; } } return $file; } /** * PHP木马防护:检查文件内容是否包含恶意代码 */ function nenghui_check_file_content($file_path) { if (!file_exists($file_path)) { return array('safe' => false, 'message' => '文件不存在'); } // 读取文件前1KB内容进行检查 $content = file_get_contents($file_path, false, null, 0, 1024); if ($content === false) { return array('safe' => false, 'message' => '无法读取文件内容'); } // PHP木马常用的危险函数和关键词 $dangerous_patterns = array( '/<\?php/i', '/<\?=/i', '/<\?\s/i', '/