Search code examples
phpajaxmod-rewriterequire-once

Can mod_rewrite rules modify require_once instructions in PHP?


or I misunderstanding the use of mod_rewrite?

I need several instances of a web application, the simple way could be copy all the files to another folder and modify a config file to make the connection to another database but I'm trying to change connection parameters according to subfolder

Options +FollowSymLinks
RewriteEngine On
RewriteRule xyz/config.php config.php?id=xyz [L]
RewriteRule xyz/(.*)$ $1 [QSA]

and some changes on config.php

//Default config
config['database'] = 'db1';
config['user'] = 'user1';
...
//config for xyz
if($_GET['id'] == 'xyz'){
  config['database'] = 'db2';
  config['user'] = 'user2';
  ...
}

There is a php file to response to all Ajax requests called ajax.php

require_once('config.php');

$task = $_GET['task'];    

if($task == 'some_task'){
  //Task according to ajax request
} else ($task == 'another_task'){
  //...
}

Solution

  • No. mod_rewrite happens before PHP execution begins and only affects how Apache serves files (it does not actually change anything in the filesystem so it does not affect PHP).

    However, you can use the $_SERVER['REQUEST_URI'] parameter, which will show you the result of the rewrite, to determine with config file to load.

    E.g.

    if(substr($_SERVER['REQUEST_URI'], 0, 4) == 'xyz/') {
         $config = include('/path/to/xyz/config.php');
    }
    else if(substr($_SERVER['REQUEST_URI'], 0, 4) == 'abc/') {
         $config = include('/path/to/abc/config.php');
    }
    

    ...etc