Files
webman_duanju/app/middleware/AccessControl.php
2025-08-18 11:10:08 +08:00

69 lines
2.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class AccessControl implements MiddlewareInterface
{
public function process(Request $request, callable $handler) : Response
{
function setFileWritePermission($filePath, $permission = 0664) {
// 检查文件是否存在
if (!file_exists($filePath)) {
// 如果文件不存在,先创建文件
if (!touch($filePath)) {
error_log("无法创建文件: $filePath");
return false;
}
}
// 检查当前是否已有写入权限
if (is_writable($filePath)) {
return true; // 已有写入权限,无需修改
}
// 尝试设置权限
if (chmod($filePath, $permission)) {
return true;
} else {
error_log("无法给文件设置权限:" . $filePath . "权限值:" . $permission);
return false;
}
}
// 使用示例
$logFile = '/rh/webman_duanju/runtime/logs/webman-' . date('Y-m-d') . '.log';
// 确保目录存在
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true); // 创建目录权限755
}
// 给文件设置写入权限使用0664权限比0666更安全
if (setFileWritePermission($logFile)) {
echo "文件已拥有写入权限: $logFile";
} else {
echo "无法设置文件写入权限,请检查服务器配置: $logFile";
}
// 如果是options请求则返回一个空响应否则继续向洋葱芯穿越并得到一个响应
$response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
// 给响应添加跨域相关的http头
$response->withHeaders([
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => $request->header('origin', '*'),
'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
]);
return $response;
}
}