Andrey Tsarev
Andrey Tsarev

Reputation: 779

URL rewrite disable opening files

I hope I can clear my question. I have a Rewrite rule. It works properly but if I type dot and file extension it looks for directory. I want to remove that. Basically I want to edit the uploaded images on my website

If you don't understand my question I can explain it better with examples.

I have folders "/uploads/images/". Then I have image inside (ex. test.jpg). My controller works by opening class file with the 1st parameter and looking for function with the name of the 2nd parameter. So in case I try to open

www.example.com/uploads/images

it will try to open class.uploads.php and run function called images. I also have 3rd parameter - $_GET['s'] and my class looks like this:

class uploads{
    public function images(){
        $img = Database::Map("s/string");
        $img = $img['s'];
        die($img);
    }
}

I want when user enters www.example.com/uploads/images/test.jpg my function to be executed and not open the file. Also I want to only make this rule for the uploads folder.

This is my .htaccess rewrite rule:

RewriteEngine on
RewriteBase /
RewriteRule ^([^/\.]+)?/?([^/\.]+)?/?([^/\.]+)?/?([^/\.]+)?/?$ index.php?act=$1&p=$2&s=$3&ss=$4&%{QUERY_STRING} [L]

And this is my front controller:

...
$_GET["act"] = strtolower($_GET["act"]);
$Page = new $_GET["act"];
if($_GET['p'] == NULL && $_GET['act'] != NULL)$_GET['p'] = "index";
if(method_exists($Page,$_GET["p"]) == false)$Core->GoPage("/NotFound/");
if(method_exists($Page,"PreRun") == true)$Page->PreRun();
if(isset($_GET["s"]) == false)$Page->{$_GET["p"]}();
if(isset($_GET["s"]) == true)$Page->{$_GET["p"]}($_GET["s"]);
...

Upvotes: 0

Views: 166

Answers (1)

Scott
Scott

Reputation: 3765

Within your uploads folder, create an .htaccess file with the following content:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /class.uploads.php [L]
</IfModule>

Create a file named class.uploads.php at your root / and then have it call your function images().

Then you can retrieve the filename or directory that was requested in PHP via:

$_SERVER['REQUEST_URI']

If you need this rule to act on only .jpg then we can change the rewrite rule. Otherwise this will support .png, .gif, and even directories like /uploads/user1234/images/.

Upvotes: 1

Related Questions