Making PHP GET parameters look like directories

心已入冬 提交于 2019-12-23 09:09:28

问题


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.



来源:https://stackoverflow.com/questions/4351806/making-php-get-parameters-look-like-directories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!