PHP 内置服务器显示索引页面而不是静态文件
PHP built-in server shows index page instead of static file
我使用 Slim 3 和 Twig 使用最简单的示例创建了一个项目。
文件夹结构如下:
- public
- index.php
- style.css
index.php
中的App代码如下:
<?php
require 'vendor/autoload.php';
$app = new \Slim\App();
$container = $app->getContainer();
// Twig
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('src/views', [
'cache' => false // TODO
]);
// Instantiate and add Slim specific extension
$basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
$view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
return $view;
};
$app->get('/', function ($request, $response, $args) {
return $this->view->render($response, 'index/index.html.twig');
})->setName('index');
$app->run();
现在,问题是尝试加载 /style.css
时显示的是主页 (index/index.html.twig
)。为什么我无法访问 style.css
文件?
服务器我用的是PHP内置的开发服务器,使用命令:
php -S localhost:8000 -t public public/index.php
如何加载资产?这里有什么问题?
原因是 PHP 内置开发服务器 'dumb'。
我不得不将此检查作为 index.php
文件中的第一件事。
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
if (PHP_SAPI == 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) return false;
}
来源:https://github.com/slimphp/Slim-Skeleton/blob/master/public/index.php
我检查过的另一个选项是 运行 服务器在 public 文件夹中。您将不需要该脚本:
cd public
php -S localhost:8000
我使用 Slim 3 和 Twig 使用最简单的示例创建了一个项目。
文件夹结构如下:
- public
- index.php
- style.css
index.php
中的App代码如下:
<?php
require 'vendor/autoload.php';
$app = new \Slim\App();
$container = $app->getContainer();
// Twig
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('src/views', [
'cache' => false // TODO
]);
// Instantiate and add Slim specific extension
$basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
$view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
return $view;
};
$app->get('/', function ($request, $response, $args) {
return $this->view->render($response, 'index/index.html.twig');
})->setName('index');
$app->run();
现在,问题是尝试加载 /style.css
时显示的是主页 (index/index.html.twig
)。为什么我无法访问 style.css
文件?
服务器我用的是PHP内置的开发服务器,使用命令:
php -S localhost:8000 -t public public/index.php
如何加载资产?这里有什么问题?
原因是 PHP 内置开发服务器 'dumb'。
我不得不将此检查作为 index.php
文件中的第一件事。
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
if (PHP_SAPI == 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) return false;
}
来源:https://github.com/slimphp/Slim-Skeleton/blob/master/public/index.php
我检查过的另一个选项是 运行 服务器在 public 文件夹中。您将不需要该脚本:
cd public
php -S localhost:8000