Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making PHP GET parameters look like directories

I am trying to make it so:

http://foo.foo/?parameter=value "converts" to http://foo.foo/value

Thanks.

like image 579
wftw Avatar asked Dec 04 '10 03:12

wftw


2 Answers

Assuming you're running on Apache, this code in .htaccess works for me:

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)/$ /index.php?parameter=$1

Depending on your site structure you may have to ad a few rules though.

like image 146
bobsoap Avatar answered Sep 28 '22 08:09

bobsoap


Enabling mod_rewrite on your Apache server and using .htaccess rules to redirect requests to a controller file.

.htaccess

# Enable rewrites
RewriteEngine On
# The following two lines skip over other HTML/PHP files or resources like CSS, Javascript and image files 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# test.php is our controller file
RewriteRule ^.*$ test.php [L]

test.php

$args = explode('/', $_SERVER['REDIRECT_URL']);  // REDIRECT_URL is provided by Apache when a URL has been rewritten
array_shift($args);
$data = array();
for ($i = 0; $i < count($args); $i++) {
    $k = $args[$i];
    $v = ++$i < count($args) ? $args[$i] : null;
    $data[$k]= $v;
}
print_r($data);

Accessing the url http://localhost/abc/123/def/456 will output the following:

Array
(
    [abc] => 123
    [def] => 456
)
like image 23
leepowers Avatar answered Sep 28 '22 07:09

leepowers