Making PHP GET parameters look like directories

2019-06-18 23:58发布

问题:

I am trying to make it so:

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

Thanks.

回答1:

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.



回答2:

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
)


回答3:

Assuming you are using Apache, the following tutorials are epically helpful:

  1. .htaccess part one
  2. .htaccess part two

The second tutorial has your answer. Prepare to dig deep into a dungeon called mod_rewrite.



回答4:

Use mod rewrite rules if you are using Apache. This is better and secure way to make a virtual directory.