Home  >  Article  >  Backend Development  >  PHP怎么获取url里的自定义参数

PHP怎么获取url里的自定义参数

WBOY
WBOYOriginal
2016-06-06 20:35:091121browse

PHP怎么获取url里的自定义参数,
比如:

  1. http://www.xxx.com/cba/index.php
  2. http://www.xxx.com/abc/index.php
  3. http://www.xxx.com/bbb/index.php

分别出来的值是:

  1. cba
  2. abc
  3. bbb


http://www.xxx.com/{shop}/index.php
需要获取shop这个变量

回复内容:

PHP怎么获取url里的自定义参数,
比如:

  1. http://www.xxx.com/cba/index.php
  2. http://www.xxx.com/abc/index.php
  3. http://www.xxx.com/bbb/index.php

分别出来的值是:

  1. cba
  2. abc
  3. bbb


http://www.xxx.com/{shop}/index.php
需要获取shop这个变量

apache大概这样配置

<code>AliasMatch ^/(匹配你参数的正则表达式)/index.php  /path/to/process.php?arg=$1
</code>

然后在process.php文件里$_GET['arg'] 就是

告诉一种用过的愚蠢的办法吧
$_SERVER['PHP_SELF']取出,然后正则,详情看以看看这个链接

外加,一般PHP程序都是用框架写的把,那样的话你可以去他的文档找他定义的常量即可,实在没有就是上面的

方案1. 使用服务器的URI重写功能,参考@zonxin的答案
方案2. 在PHP中去解析URL,注意应该使用$_SERVER['REQUEST_URI'],例如:

<code>   if (preg_match('|^/([^/]+)/index.php|', $_SERVER['REQUEST_URI'], $matches)){
       list(, $shop) = $matches;
       echo $shop;        // => 你期望的shop这个变量
   }
</code>

b.t.w. 关于REQUEST_URI和PHP_SELF的区别,请参考这篇讨论

.htaccess重写url

<code>isset($_SERVER['PATH_INFO'])?explode('/',my_addslashes(ltrim(trim($_SERVER['PATH_INFO']),'/')))
</code>

可以使用PATH_INFO获取,不过不建议这么做了,现在的框架都是使用query_string

获取PATH_INFO,用正则匹配出来

<code>preg_match('/\/(.*)\/index.php/',$_SERVER['PATH_INFO'],$match);
var_dump($match[1]);
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn