Home » Php » twig – PHP built-in server shows index page instead of static file

twig – PHP built-in server shows index page instead of static file

Posted by: admin July 12, 2020 Leave a comment

Questions:

I created a project with Slim 3 and Twig using their simplest examples.

Folder structure is as follows:

- public
    - index.php
    - style.css

App code in index.php is as follows:

<?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();

Now, the problem is that trying to load /style.css shows the main page instead (index/index.html.twig). Why can I not access the style.css file?

The server I use it the PHP built-in development server, using the command:

php -S localhost:8000 -t public public/index.php

How can I load the assets? What’s the issue here?

How to&Answers:

The cause was the PHP built-in development server being ‘dumb’.

I had to include this check as the very first thing in the index.php file.

// 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;
}

Source: https://github.com/slimphp/Slim-Skeleton/blob/master/public/index.php