router.php 1.06 KB
<?php
// +----------------------------------------------------------------------
// | PHP 内置服务器路由(php think run / php -S ... public/router.php)
// +----------------------------------------------------------------------
// 旧版 is_file(DOCUMENT_ROOT . SCRIPT_NAME) 在部分 PHP 版本下会误判,导致 400。
// 按 REQUEST_URI 判断 public 下是否存在同名静态文件;否则进入 ThinkPHP。
// +----------------------------------------------------------------------

declare(strict_types=1);

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');

if ($uri !== '/' && $uri !== '' && str_contains($uri, '..')) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Forbidden';
    return true;
}

if ($uri !== '/' && $uri !== '') {
    $path = __DIR__ . str_replace('/', DIRECTORY_SEPARATOR, $uri);
    if (is_file($path)) {
        return false;
    }
}

$_SERVER['SCRIPT_FILENAME'] = __DIR__ . DIRECTORY_SEPARATOR . 'index.php';

require __DIR__ . DIRECTORY_SEPARATOR . 'index.php';