18

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?

Linksku
  • 1,449
  • 6
  • 17
  • 22
  • 6
    Short answer: You cannot. However, if your application knows the rewrite scheme (ie. you have reverse mapping) or you have well-defined rewrite rules, you can reverse the rewrite process. – Emre Yazici Jul 05 '11 at 20:47
  • 4
    @Emre `$_SERVER['REQUEST_URI']` will do the job just fine on Apache server and IIS 7.x if URL Rewrite module v2 is used. – LazyOne Jul 05 '11 at 21:56
  • why do you want this url? there may be an easier solution to accomplishing what you want to accomplish. – dqhendricks Jul 05 '11 at 22:08
  • 1
    @LazyOne You are right, I had forgotten that. – Emre Yazici Jul 05 '11 at 22:10
  • for mod_rewrite extraction & debug bookmark this link: http://www.askapache.com/htaccess/crazy-advanced-mod_rewrite-tutorial.html – regilero Jul 05 '11 at 22:22

4 Answers4

14

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

Cfreak
  • 19,191
  • 6
  • 49
  • 60
  • `$_SERVER['QUERY_STING'];` contains the query string exactly as it was sent. No need to recompose it. This could be more simply expressed as. `$url = implode('?', array_filter([$_SERVER['PHP_SELF'], $_SERVER['QUERY_STRING']]));` – tvanc Apr 08 '19 at 16:03
  • -1, because carpereret's answer gives something else and yours is the correct answer. I don't know why you edited your post and made it invalid. You should remove it. – Arda Kara Jun 26 '19 at 21:32
9

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

carpereret
  • 149
  • 1
  • 1
  • 5
  • Good one. Also, this will give your the full url shown on the browser's address bar in case you are rewriting it. – LuBre Feb 01 '16 at 19:11
  • 2
    This does the opposite of what the OP asked for. OP is asking how to get the URL as it was rewritten, not its original form. – tvanc Apr 08 '19 at 15:53
1

Here is how to get the URL received by PHP after being rewritten with mod_rewrite in Apache:

 $url = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

You can compare this url with the actual url in the browser to debug any rewrite rules in .htaccess

Andyba
  • 421
  • 3
  • 10
1

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'];
Vitaly
  • 56
  • 8