使用内置PHP服务器使用超薄应用程序v3提供静态文件

问题描述 投票:0回答:1

我正在使用Slim框架开始一个新项目。到目前为止,它正在变得体面,我在微框架中寻找的一切。我已经离开了PHP世界一段时间,所以我现在开始了解内置的PHP Web服务器。唯一的问题是:我如何提供我的静态内容?

作为参考,这是我的项目布局:

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

虽然这很好用,但当我尝试访问我的静态内容时,它只返回渲染的base.html文件

请让我知道开始这个的最佳方式,以便正确呈现静态内容。非常感谢您的帮助。

php slim
1个回答
0
投票

因此,基于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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.