PHP include () affected by mod_rewrite

I inherited several heavily encoded PHP files, the output of which I need to programmatically modify.

To achieve this, I decided to run them through another PHP file rewriter.php, which looks something like this:

<?php
if(!preg_match('/^([a-zA-Z0-9\-_]*)$/', $_GET['page']))
  die('Incorrect page supplied.');
ob_start('changeOutput');

include($_GET['page'].'.php');
ob_end_flush();

function changeOutput ($buffer) {
  ...
}
?>

      

I am using mod_rewrite to get them to work through this file:

RewriteEngine On
RewriteRule ^([^\.]*)\.php$ rewriter.php?page=$1 

      

However, an error message is displayed, which is why I believe the include () operation is affected by the RewriteRule above, i.e. it tries to run rewriter.php through rewriter.php etc.

I guess there are many ways to solve this problem, but I am specifically looking for a way to avoid the include () expression due to the influence of mod_rewrite. I have looked through the documentation for the module, but I couldn't find anything suitable.

Of course, alternatives to this approach are also welcome.

Thanks for your time and reflection.

Regards,
Daniel

0


a source to share


4 answers


It looks like you are looking for RewriteCond, which is essentially a conditional expression for mod_rewrite

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !rewriter.php$
RewriteRule ^([^\.]*)\.php$ rewriter.php?page=$1 [L]

      



This will prevent your rule from being applied to URLs that end in rewriter.php.

+2


a source


You must first check if the file exists before including it:



if ($_GET['page'] != 'rewriter' && is_file($_GET['page'].'.php')) {
    include $_GET['page'].'.php';
} else {
    // file does not exist or is invalid
}

      

+1


a source


You can add a RewriteCond to your htaccess that will check if the file exists. Similar to Gumbo's comment, except for slightly faster (and lighter code).

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([^\.]*)\.php$ rewriter.php?page=$1

      

This checks if it is a file or a directory relative to the root of your site. If so, it will start overwriting. Quick touch .htaccess awesomeness :)

0


a source


Include, as you do, reference the filesystem and bypass the mod-rewrite conversion mechanism.

I would look at your regex.

/^([a-zA-Z0-9\-_]*)$/ 

      

also enter an empty string.

Try

/^([a-zA-Z0-9\-_]+)$/ 

      

and see if it's empty or not. $ _GET ['page'].

-1


a source







All Articles