Php include() proper Mime-types - php

TLDR: I'm looking for a way to serve web resources (css, jpg, etc) from the filesystem that preserves mime-type.
I am creating a php wrapper that validates a user from another domain (via a one time token), creates a session and then serves files, several websites in separate directories, inside of a otherwise in accesable directory to that user.
I have, so far, used php to handle validation and mod_rewrite to redirect all requests for anything inside of the directory through the wrapper adding the requested page as a get.
The problem is, when I open a webpage that links to other resources it runs through the wrapper for each resource and doesn't preserve the mime-type. As a result formating gets screwed up.
Does anyone have a work around or a better way to serve files from the filesystem via a php script.
Here are my Redirect rules:
<Directory /var/www/ssl/auth>
RewriteEngine On
RewriteBase /auth
RewriteRule ^(.*) /wrapper.php?topage=https://%{SERVER_NAME}/auth/$1
</Directory>
And This is the include: (after it's been checked that the file exists)
$path = 'https://'.$_SERVER['SERVER_NAME'].'/';
$abs_path=substr($_GET['topage'], strlen($path));
include ($abs_path);
Here are the errors I'm getting (using dev tools on chrome)
Resource interpreted as Stylesheet but transfered with MIME type text/html
I am creating this so apple users at my school can publish class websites (using iweb and hosted internally) that require authentication and can be accessed without signing in twice when linked from the school's main website (externally hosted).
The suits are adamant that they want it setup to cross domains.
If you have any suggestions to this particular problem or how to achieve auth. across domains let me know.
Solution
Tandu. Thanks for the help using the concepts you laid out I was able to use stack overflow to solve my problem here is the solution. I < and found how to get the mime type and then I relayed it using header() works like a charm.
$path = $proto.$_SERVER['SERVER_NAME'].'/';
$abs_path=substr($_GET['topage'], strlen($path));
$type = (get_object_vars(apache_lookup_uri("$abs_path")));
header('Content-type: '.$type['content_type']);
readfile($abs_path);
Hope this helps someone down the line.

Well, I'm not sure if I can answer your full question, but the problem in Chrome is that your server is sending the file as the wrong MIME type (obviously). You need to update your server settings to send the correct mime type for css, js, etc. files. It is difficult to guess the mime type for css, js, etc. because they don't have the mime information stored in the file headers and instead you must guess. You can configure apache to set the mime type based on the extension with the mime.types.

Related

Do browsers ignore suffixes?

By mistake, I did not add the suffix .php when I wrote a URL into the browser during a check on my website. The browser ignored it and simply returned the page as if I had added the .php suffix, anyway! Is this normal? Do all modern browsers see a URL like www.website.com/thispage and simply go to thispage.php or thispage.html, if they exist?
Requests go to the server.
Any basic URL in the address bar of a browser make an HTTP request to the server defined by the domain (or hostname). So, http://www.something.com/here/there.x sends a whole bunch of info (in the "HEADER" of the request) to the IP registered for the www subdomain of something.com. That server gets the request, which in the header includes information about your browser, IP, type of request, the full address requested, any submitted data from a form, etc.
Your server's http engine decides what to do with it
Apache, nginx, iis, are different types of HTTP servers who's whole purpose are to listen for such requests, and decide what to do about them.
Typically, this includes setting some degree of defaults, for instance:
match the domain to a directory
something.com: /var/www/site1
strange.com: /var/www/site2
default: /var/default
match the path (everything after the '/' following the domain) to a file
check for a matching .html file
check for a matching .php file
Check permissions and authentication
Execute the file according to config
send the php file to a php process, and reroute the output
simple grab and dump the contents of images, txt, and html files.
Send a response according to what was just executed.
This is DRASTICALLY simplified, and there are many many layers and specifics, but I'm trying to keep this as simple as the question.
You tell apache (or whatever) what to do.
Apache can be configured to return a styleized google search for cats, any time anyone requests `http://blah.something.com/[anything]/*.good. It can be configured to do just about anything you want it to, based on the url you send it. The browser only decides what is sent.
It is completely up to the web server, and it's configuration, as to how a URL is handled. Web servers like Apache, NGinx, Cherokee, Litespeed, etc all have different mechanisms for what happens when a URL request hits it, and then what it decides to do afterwards.
For instance, you could have your web server attempt to add .php and .htm and .html suffixes to the requested url, in order to try to be helpful. Or simply serve up the 404 page, or send the request to the home page - eg index.php.

Deny direct access to files using htaccess

I have below directory structure in my website,
/public_html
/public_html/admin/
/public_html/admin/js/
/public_html/admin/css/ ....
Basically I want to disallow all direct access to files inside sub folders of /admin, like not allow to access js inside /js/ folder directly but allow it to access from my php page
I added .htaccess file with below code inside /js/ folder,
Order deny,allow
Deny from all
so it is good that it won't allow me to access via browser directly !
BUT when I try to access index.php page in which files of /js/ folder are included using tag, it is not loading up.
So can anyone help me out !
Thanks in advance.
You are not accessing it "from your PHP page". The web server is either serving a request or it isn't. When you load your "PHP page" in a browser, the browser will then go out and request all the Javascript, CSS and image assets linked to from your page. Each of these will be a separate HTTP request to the web server. The web server has no context that this HTTP request is because the asset is linked to from "your PHP page", that's completely irrelevant to it. You can either get the file from the server using an HTTP request, or you can't. And by setting Deny from all, you can't.
You'd have to funnel all requests through a PHP file which checks the login information and only serves the file if the user is properly logged in. E.g. link to scripts.php?file=js/myscript.js and have authentication checking code in scripts.php.
When you restrict a folder like this, you can not include the files that are in it inside your HTML page. It is basically the same request as if the person is accessign directly to the JS by URL.
Usually cpanel tools like
Hotlink Protection
Hotlink protection prevents other websites from directly linking to files (as specified below) on your website. Other sites will still be able to link to any file type that you don't specify below (i.e., HTML files). An example of hotlinking would be using an <img> tag to display an image from your site somewhere else on the Web. The end result is that the other site is stealing your bandwidth.
Index Manager
The Index Manager allows you to customize the way a directory will be viewed on the web. You can select between a default style, no indexes, or two types of indexing. If you do not wish for people to be able to see the files in your directory, choose "No Indexing".
1&2 are tools from usual hosting cpanel. Probably it writes over apache conf files(not sure which ones)
However, you should also be aware of HTTP referer. You could based on this decide when not to show your respurce.
`HTTP referer is an HTTP header field that identifies the address of the webpage (i.e. the URI or IRI) that linked to the resource being requested`

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

How can I block direct access to my JavaScript files?

I use Minify to minify and cache all my script requests. I only want my users to be able to access the minified versions of the JavaScript files.
Minify lies at www.example.com/min and my scripts are at www.example.com/scripts. How can I block direct access to doc_root/scripts which is where my unminified JavaScript files lie. I'd rather not put them out of the document root but it's an option.
Please note that I'm using Zend Framework, so the actual root of my application is shifted to www.example.com/public. An htaccess file handles the rewrite.
Can't you just use an .htaccess file inside doc_root/scripts to prevent all access over the web to .js files over HTTP?
It won't stop minify, since that provides indirect access.
So in doc_root/scripts/.htaccess, something along the lines of
<Files ~ "\.js$">
order allow,deny
deny from all
</Files>
Note that the location of the .htaccess file matters in this case.
You effectively can't block end-user facing code. Even if you served it with PHP or another server-side language and blocked direct requests, it's of course still possible to read it directly with a number of tools.
You should code with this in mind and be mindful with javascript comments, business knowledge, etc.
UPDATE:
However, if you're talking about code that doesn't ever need to be accessed by an end-user, you could as you mentioned move it out of the server root, or you can block the files in your directory (or an entire directory). It's easy with Apache's .htaccess.
order deny, allow
deny from all
You could also redirect the source files to the minified versions with mod_rewrite in your .htaccess file.
RewriteEngine On
RewriteRule /scripts/(.*)$ /min/$1 [L,NC]
Depends on the server you're using. Assuming it's Apache, you can add this to your .htaccess file:
<Directory ~ "\scripts">
Order allow,deny
Deny from all
</Directory>
Or something to that effect..
The only way is to check referers, and not everyone sends them, or sends a real one. In other words, you can't block direct access to anyone who really wants something. It's impossible to determine with 100% accuracy if a request is a direct one or is being done via a <script src=....> type request.
For your Javascript to actually run the user's browser must be able to read it ultimately.
As such there's no real way to "block" access to your scripts folder (well to be precise you can but that would break your website since the browser would not see the files in order to run them.)
One solution could be obfuscation, which makes the javascript code harder to read / understand but ultimately the user will see the code, and with a bit of persevering reverse engineering it can be de-obfuscated.
Another thing i've seen someone do is creating an "empty" js.html page, and insert all their javascript into script tags in the page (embedded, not external), and from his main page make ann ajax request to js.html and embed it at the bottom of the page. kind of a round about way but the user will not see the js when viewing the source unless using developper tools such as firebug.
Note that the last option also might cause some delay depending on the abount of code you are loading. but here the key is not blocking access to your scripts, but just making them harder to obtain / read / copy.
Edit: oops, misread as well. I think the best solution in this case would be to go with an htaccess file in your scripts folder denying all access
This answer is little bit newer, than question (only several years, that’s nothing)
You cannot deny access to JavaScript file, because they wont’t be accessible from <script> tag.
But I found a workaround:
RewriteEngine On
RewriteRule ^.*\.js$ /invalid.html [R=301,L]
Place it in your .htaccess file in your home folder of web. (under htdocs or public_html).
This will automatically redirect everyone from it. So they don’t see it.

Point an <img> tag to a image dynamically generated by PHP?

Is it possible to redirect an image to a dynamically generated image(using PHP)?
I have a dynamically created image and it has an extension ".PHP" (obviously) and that server is not under my control. So I want to redirect "somename.jpg" (on my server) to "remoteserver/dynamicimage.php" (on some remote server not under my control) so that I can right away link it as <img src="somename.jpg"/> and the dynamically generated image is shown.
Please let me know if this is possible.
Browsers follows redirects for images. Create a php-file called "somename.jpg" and add:
<?php
header('Location: http://www.otherserver.com/image.php');
Use the Apache directive ForceType in an .htaccess file to tell the server to process the .jpg file as php:
<Files somename.jpg>
ForceType application/x-httpd-php
</Files>
Or just call the file somename.php if you don't really need the .jpg extension.
You could probably accomplish this using mod_alias as well, although I haven't tried it:
Redirect somename.jpg http://www.otherserver.com/image.php
This would go in an .htaccess file as well.
The header function controls the HTTP header, which is what the browser uses to determine the file type (or should, in any case.) It can be used to tell the browser that the script is generating an image file to be downloaded, rather than HTML script output:
header('Content-type: image/jpeg');
header('Content-Disposition: attachment; filename="somename.jpg"');
Try adding something like this to your .htaccess file
RewriteEngine on
RewriteRule ^(.*)\.jpg$ /scripts/$1.php
It is possible but would result in an HTTP redirect:
RewriteEngine on
RewriteRule ^somename\.jpg$ http://remoteserver/dynamicimage.php [L]
An alternative would be to use a proxy (see P flag), so that your server requests the remote resource and passes it back to the client.
Another much more complicated but incredible powerfull way would be to write some handler code which gets activated for this local image location url.
This one would fetch the data from the foreign url and outputs the data with the right mime type.
One you also write some code to cache this data basing on whatever may be feasible.
This way you would never give away the real location of the image and you could even use some secret credentials like logindata or third party cookies which should not appear on your site.
All of this is much harder to do then to simply configure a redirection in the apache config. We did stuff like this in cases where the url's would leak private informations otherwise.

Categories