使用内置 PHP 服务器为 Slim 应用程序 v3 提供静态文件
Serving Static Files with Slim Application v3 Using Built In PHP Server
我正在使用 Slim 框架开始一个新项目。到目前为止,它进展顺利,我在微框架中寻找的一切。我已经离开 PHP 世界一段时间了,所以我现在开始了解内置的 PHP 网络服务器。唯一的问题是:如何提供我的静态内容?
供参考,这是我的项目布局:
project:
public folder
index.php
static/css/style.css
templates/index.html . # I'm using twig (coming from python Flask)
我的模板:
<html>
<link href="{{ base_url() }}/css/agency.css" rel="stylesheet">
<!-- other cool layout stuff -->
和我的 index.php(非常小)
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/', function ($request, $response, $args) {
$response = $this->view->render($response, 'base.html');
return $response->write("Hello ");
});
$app->run();
当我从命令行启动内置 php 服务器时,我这样做:
php -S localhost:8080 -t public public/index.php
虽然这很好用,但当我尝试访问我的静态内容时,它只是 returns 呈现的 base.html 文件
请告诉我开始此操作的最佳方式,以便正确呈现静态内容。感谢您的帮助。
所以根据 kuh-chan 和 Nima 指出的文档,我将其扩展用于 Slim 目的,如果文件不存在则返回 404 响应。
if (PHP_SAPI == 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
// check the file types, only serve standard files
if (preg_match('/\.(?:png|js|jpg|jpeg|gif|css)$/', $file)) {
// does the file exist? If so, return it
if (is_file($file))
return false;
// file does not exist. return a 404
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
printf('"%s" does not exist', $_SERVER['REQUEST_URI']);
return false;
}
}
我正在使用 Slim 框架开始一个新项目。到目前为止,它进展顺利,我在微框架中寻找的一切。我已经离开 PHP 世界一段时间了,所以我现在开始了解内置的 PHP 网络服务器。唯一的问题是:如何提供我的静态内容?
供参考,这是我的项目布局:
project:
public folder
index.php
static/css/style.css
templates/index.html . # I'm using twig (coming from python Flask)
我的模板:
<html>
<link href="{{ base_url() }}/css/agency.css" rel="stylesheet">
<!-- other cool layout stuff -->
和我的 index.php(非常小)
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/', function ($request, $response, $args) {
$response = $this->view->render($response, 'base.html');
return $response->write("Hello ");
});
$app->run();
当我从命令行启动内置 php 服务器时,我这样做:
php -S localhost:8080 -t public public/index.php
虽然这很好用,但当我尝试访问我的静态内容时,它只是 returns 呈现的 base.html 文件
请告诉我开始此操作的最佳方式,以便正确呈现静态内容。感谢您的帮助。
所以根据 kuh-chan 和 Nima 指出的文档,我将其扩展用于 Slim 目的,如果文件不存在则返回 404 响应。
if (PHP_SAPI == 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
// check the file types, only serve standard files
if (preg_match('/\.(?:png|js|jpg|jpeg|gif|css)$/', $file)) {
// does the file exist? If so, return it
if (is_file($file))
return false;
// file does not exist. return a 404
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
printf('"%s" does not exist', $_SERVER['REQUEST_URI']);
return false;
}
}