I use mod-rewrite
to make pretty URLs, like http://example.com/users/Dan etc.
I need to fetch the rewrite rule for the supplied URL to find the path for the server-side file that is requested; however, this is not taking place on the active page so I cannot use $_SERVER['REQUEST_URI']
, $_SERVER['PHP_SELF']
, or ___FILE____
.
I need to do something like this:
$url = '/users/Dan';
$path = $_SERVER['DOCUMENT_ROOT'].'/'.get_filepath_from_htaccess($url);
In this case, if you go to http://example.com/users/Dan you are actually viewing http://example.com/user.php?name=Dan
So, in this case, get_filepath_from_htaccess()
should return /user.php?name=Dan
.
I thought about running through the .htaccess file with a regex, but many of the rewrites are dynamic so it would be quite messy I imagine and I'm hoping there's a cleaner solution.
UPDATE I realize that my original question was not precise enough and my intentions were not clear. To be clear, this is exactly what the script will be used for.
On my site, users can create custom URLs and point them to existing URLs. For example, my profile would be located at example.com/users/Dan. But, when I create a custom URL (example.com/DansCustomURL) and point it to my profile, it should fetch the page contents from the profile without forwarding to example.com/users/Dan
So, here's how it goes.
A 404 first redirects to url.php
which scans the database for custom URLs matching the requested URL. If one is not found, the 404 page is displayed instead.
If a file is found, url.php
needs to determine the filepath for the target URL.
Ok So I am making some assumptions here:
I think the information that you are looking for i.e /user.php?name=Dan
can be extracted through $_SERVER.
So now what you will need is the get_filepath_from_htaccess
function, and this function should be available on all of your files..
If you have a common file like config.php, functions.php, which is available(included or required) in all of the pages like user.php, admin.php etc.
Then you need to place this function in the common file, and your function could look like
function get_filepath_from_htaccess() {
return $_SERVER['SCRIPT_FILENAME'] .
(isset($_SERVER['REDIRECT_QUERY_STRING']) ?
'?' . $_SERVER['REDIRECT_QUERY_STRING'] : '');
}
This will give the complete path from system root, so you will not have to append $_SERVER['DOCUMENT_ROOT']
.
You might have to make a few changes to the code according to your server configuration so just take a dump(print_r or var_dump) of $_SERVER and extract out the information that you require and update the above function