Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

twig

slim

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?

like image 284
Tarps Avatar asked Oct 04 '17 15:10

Tarps


2 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

like image 93
Tarps Avatar answered Oct 01 '22 16:10

Tarps


Another option I checked an works is run server inside public folder. You will not need that script:

cd public
php -S localhost:8000
like image 43
Eagle Avatar answered Oct 01 '22 14:10

Eagle