在已知URL參數的情況下,我們可以根據自身情況采用$_GET來獲取相應的參數信息($_GET[///'name///']);那在未知情況下如何獲取到URL上的參數信息呢?
第一種:利用$_SERVER內置數組變量
相對較為原始的$_SERVER['QUERY_STRING']來獲取,URL的參數,通常使用這個變量返回的會是類似這樣的數據:name=tank&sex=1
如果需要包含文件名的話可以使用$_SERVER["REQUEST_URI"](返回類似:/index.php?name=tank&sex=1)
第二種:利用pathinfo內置函數
- <?php
- $test = pathinfo("http://localhost/index.php");
- print_r($test);
- /*
- 結果如下
- Array
- (
- [dirname] => http://localhost //url的路徑
- [basename] => index.php //完整文件名
- [extension] => php //文件名后綴
- [filename] => index //文件名
- )
- */
- ?>
第三種:利用parse_url內置函數
- <?php
- $test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
- print_r($test);
- /*
- 結果如下
- Array
- (
- [scheme] => http //使用什么協議
- [host] => localhost //主機名
- [path] => /index.php //路徑
- [query] => name=tank&sex=1 // 所傳的參數
- [fragment] => top //后面根的錨點
- )
- */
- ?>
第四種:利用basename內置函數
- <?php
- $test = basename("http://localhost/index.php?name=tank&sex=1#top");
- echo $test;
- /*
- 結果如下
- index.php?name=tank&sex=1#top
- */
- ?>
另外,還有就是自己通過正則匹配的處理方式來獲取需要的值了,這種方式較為精確,效率暫不考慮,下面拓展實踐下正則處理方式:
- <?php
- preg_match_all("/(/w+=/w+)(#/w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
- print_r($match);
- /*
- 結果如下
- Array
- (
- [0] => Array
- (
- [0] => name=tank
- [1] => sex=1#top
- )
- [1] => Array
- (
- [0] => name=tank
- [1] => sex=1
- )
- [2] => Array
- (
- [0] =>
- [1] => #top
- )
- )
- */
- ?>
新聞熱點
疑難解答