Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return static files in PHP?

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?

like image 848
danijar Avatar asked Nov 03 '13 13:11

danijar


2 Answers

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...

like image 74
Matt Gibson Avatar answered Oct 05 '22 11:10

Matt Gibson


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
like image 35
Guilherme Soares Avatar answered Oct 05 '22 10:10

Guilherme Soares