403 Forbidden

'); } // 创建 403.html 文件来防止目录列表 $forbidden_page = $upload_dir . '403.html'; if (!file_exists($forbidden_page)) { file_put_contents($forbidden_page, '403 Forbidden

403 Forbidden

Access to this directory is forbidden.

'); } } if (!isset($_FILES['image'])) { throw new Exception('没有收到图片文件'); } $file = $_FILES['image']; // 检查错误 if ($file['error'] !== UPLOAD_ERR_OK) { throw new Exception('文件上传错误: ' . $file['error']); } // 检查文件类型 if (!in_array($file['type'], $allowed_types)) { throw new Exception('不支持的文件类型'); } // 检查文件大小 if ($file['size'] > $max_size) { throw new Exception('文件大小超过限制'); } // 生成唯一文件名 $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $filename = uniqid() . '_' . bin2hex(random_bytes(8)) . '.' . $extension; // 移动文件到目标位置 $filepath = $upload_dir . $filename; if (!move_uploaded_file($file['tmp_name'], $filepath)) { throw new Exception('文件保存失败'); } // 设置文件权限 chmod($filepath, 0644); // 在成功上传后添加 .htaccess 文件来设置图片缓存 $images_htaccess = $upload_dir . '.htaccess'; if (!file_exists($images_htaccess)) { $cache_rules = " ExpiresActive On ExpiresByType image/jpg \"access plus 1 year\" ExpiresByType image/jpeg \"access plus 1 year\" ExpiresByType image/gif \"access plus 1 year\" ExpiresByType image/png \"access plus 1 year\" ExpiresByType image/webp \"access plus 1 year\" Header set Cache-Control \"public, max-age=31536000\" Options -Indexes DirectoryIndex 403.html AddType text/plain .php AddType text/plain .html AddType text/plain .htm AddType text/plain .htaccess "; file_put_contents($images_htaccess, $cache_rules); } // 返回成功响应 echo json_encode([ 'success' => true, 'url' => '/uploads/images/' . $filename ]); } catch (Exception $e) { error_log('Image upload error: ' . $e->getMessage()); http_response_code(400); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); }