Use PHP/Apache to restrict access to images
First, I know this is NOT a new topic, or even a duplicate that was discussed, but I want to propose a new aproach, that I don't know how to implement:
My idea is the following:
- APACHE should deliver the file not PHP. This is highly critical
- PHP should just do the authentication and re-send/forward the request with some trick/variable set)
- the same-request is being re-sent and this second time the Rewrite Conditions should fail(due to the trick) and the file should be directly delivered.
Steps:
- request is coming in(URL = http://somedomain.com/files/image1.png), apache forwards it to access.php
- access.php checks that the user has access to the file
- IF check is successful, then PHP sets an environment variable AUTHORIZED = true and makes an internal re-direct to the original URL.
- Same request is coming in (SECOND time - this time with AUTHORIZED set) -> RewriteCond will NOT match(RewriteCond %{ENV:AUTHORIZED} !^$), and the file will be delivered.
I am not sure how to make a proper link between step 3 and 4. Not sure how that would be possible.
I am not sure what kind of mechanisms are available from PHP to set an apache environment variable, or something similar.
Any input would be appreciated.
Code samples:
.htaccess
RewriteEngine on
RewriteCond %{ENV:AUTHORIZED} !^$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ access.php [L]
access.php
if ( 1 == 1 /* check if user is authorized*/ ) {
// set an environment variable for apache!!!
apache_setenv( 'AUTHORIZED', "true" ); //not working!
//forward the request
header( "Location:" . $_SERVER[ 'REQUEST_URI' ] );
exit;
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
Some references:
Using PHP/Apache to restrict access to static files (html, css, img, etc)