PHP 内置服务器显示索引页面而不是静态文件

标签 php twig slim

我使用 Slim 3 和 Twig 使用最简单的示例创建了一个项目。

文件夹结构如下:

- public
    - index.php
    - style.css

index.php中的应用代码如下:

<?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

如何加载 Assets ?这里有什么问题?

最佳答案

原因是 PHP 内置开发服务器“愚蠢”。

我必须将此检查作为 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

关于PHP 内置服务器显示索引页面而不是静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568528/

相关文章:

php - 更新功能不起作用

symfony - 解决关于 $this 的弃用 - get ('twig' )-> getextension ('form' )

php - 找不到 Slim 类。我不确定这里做错了什么

php - Slim Framework 与 WordPress 正确设置 htaccess

php - 迁移后 Drupal 站点非常慢

javascript - PHP 表单验证与 ajax

Symfony 2 和 twig : Add a class for 'current page' in navigation

php - 多个 if-else if 语句 Twig

php - 如何在路由执行前后修改 slim v3 响应体?

javascript - 在 PHP 中将本地镜像 blob 转换为 base64