Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How can I get the URL that has been rewritten with mod_rewrite?

For example, if I rewrite /category/topic/post/ to /index.php?cat=1&topic=2&post=3, how can I get /index.php?cat=1&topic=2&post=3 using PHP?

like image 218
Linksku Avatar asked Jul 05 '11 20:07

Linksku


People also ask

What is URL rewrite in Apache?

URL rewriting purpose is to change the appearance of the URL to a more user-friendly URL. This modification is called URL rewriting. For example, http://example.com/form.html can be rewritten as http://example.com/form using URL rewriting.

What does Mod rewrite do?

mod_rewrite provides a flexible and powerful way to manipulate URLs using an unlimited number of rules. Each rule can have an unlimited number of attached rule conditions, to allow you to rewrite URL based on server variables, environment variables, HTTP headers, or time stamps.


3 Answers

You can recreate it pretty easily. $_SERVER['PHP_SELF'] will still give you the correct file name for the script. This should do the trick:

$url = $_SERVER['PHP_SELF'];
$parts = array();
foreach( $_GET as $k=>$v ) {
    $parts[] = "$k=" . urlencode($v);
}

$url .= "?" . implode("&", $parts);

$url will now be the URL you're looking for.

EDIT: @carpereret's answer is far better. Upvote him instead

like image 124
Cfreak Avatar answered Sep 23 '22 17:09

Cfreak


original uri should be in $_SERVER['REQUEST_URI']

like image 38
carpereret Avatar answered Sep 19 '22 17:09

carpereret


You can set environment variable in mod_rewrite rule and then use it in PHP. Example:

mod_rewrite:

RewriteEngine on
RewriteRule ^/(category)/(topic)/(post)/$ /index.php?cat=$1&topic=$2&post=$3 [L,QSA,E=INDEX_URI:/index.php?cat=$1&topic=$2&post=$3]

PHP:

$index_uri = $_SERVER['INDEX_URI'];
like image 40
Vitaly Avatar answered Sep 23 '22 17:09

Vitaly