How can I return static files in PHP?

亡梦爱人 提交于 2019-12-14 03:53:33

问题


I use a .htaccess file to redirect all requests to the same index.php. From there, I decide what to do depending on URL of the incoming request.

For now, I map the request URL to directory structure relative to a source folder, so that example.com/user/create maps to source/user/create/index.php. The file located there can handle the request as needed, and generate HTML output.

But that doesn't work for static assets, the browser may request. So my idea is to find out whether a request URL ends with a file extension and map that to a directory structure relative to a assets folder, so that example.com/css/default.css would map to assets/css/default.css. But I don't know how to respond with a static file instead of HTML code from PHP.

Normally, this might be done using an additional .htaccess rule, but I'd like to change the assets folder dynamically in code.

How can I send a static file, given on the server's hard drive, to the browser client in PHP?


回答1:


On the the htacess

#Expections
RewriteCond %{REQUEST_URI} ^/assets.*$
RewriteRule ^(.*)$ - [L,NC]

#You redirect to index
...

put a / at the beginning of the file path

/assets/path/to/file



回答2:


Well, if you really want to, you can just use readfile(). But it would be better to let the web server handle static files if you can; it's more efficient than firing up PHP just to throw a file out the door.

Also, with the PHP approach you'll probably have to set the Content-Type header appropriate per file, which can be annoying. Your web server will be doing that for you already when serving files directly.

Plus there are other things that you may be getting for "free" at the moment that you'll have to consider -- using ob_gzhandler if you want to compress your pages, as might already be being done for static files by Apache, say.

So, while it's possible, and I can see reasons why it's sometimes desirable, I'd probably try to make this kind of processing the exception rather than the rule for files that aren't generally dynamic...



来源:https://stackoverflow.com/questions/19753315/how-can-i-return-static-files-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!