is there a PHP function to simulate how apache mod_rewrite works?
I'm pretty stuck in here, so what I need is a function or, an idea to create a function, to work pretty the same way as mod_rewrite of Apache. It is supposed to have as param a regexp, writtten for mod_rewrite, and the url. Should return an array of parameters extracted from it.
Here's a short example of how it should work:
function rewrite($regexp, $url){
....
}
$params = rewrite('([^/]+)-([^/]+).html', 'Oval-Shape.html');
print_r($params);
The code above should print:
ar开发者_JS百科ray(1=>Oval, 2=>Shape)
Yes, RewriteRule
uses a perl compatible regular expression. That's the same PHP does in preg_match()
.
A difference is, that in ModRewrite
you can prefix it with a !
to not match something.
Another thing is, when you add the NC
flag, they are case in-sensitive. In a PHP regex this can be achieved by using the i
modifier.
So before you start re-invent the wheel, why not choose that function? It works like this:
$url = 'Oval-Shape.html';
$regexp = '([^/]+)-([^/]+).html';
$result = preg_match("({$regexp})i", $url, $params);
print_r($params);
And this is the output:
Array
(
[0] => Oval-Shape.html
[1] => Oval
[2] => Shape
)
So $params[1]
is what you know as $1
in .htacces and so on.
This behaviour can be easily replaced with PHP and allows more flexible and complex rules, for example based on database records.
Put this in your .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
This way, every request is forwarded to index.php. You can then get and parse the $_SERVER['REQUEST_URI']
variable and forward the page execution wherever you want to.
This is what every current MVC framework does. It's called routing.
You will not be able to fully simulate Apache's mod_rewrite
because Apache will rewrite the Url before dispatching the request, whereas when PHP is ivoked, the request has already been dispatched. For example, if you request
/index.php?page=mypage
with an .htaccess
like
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*)$ index.php?page=$1 [NC,L]
You could also request the same Url with
/mypage
Which would result in index.php
be called with $_SERVER['REQUEST_URI'] = '/mypage'
and $_GET['page'] = 'mypage'
.This behavior cannot be replicated by PHP because Apache will not find mypage
and will issue an error 404.
精彩评论