PHP擷取解析URL方法

來源:互聯網
上載者:User

  通過url進行傳值,是php中一個傳值的重要手段。所以我們要經常對url裡面所帶的參數進行解析,如果我們知道了url傳遞參數名稱,例如:

  /index.php?name=tank&sex=1#top

  我們就可以通過$_GET['name'],$_GET['sex']來獲得傳的資料。但是如果我們不知道這些變數名又怎麼辦呢?這也是寫這篇博文的目的,因為自己老是忘,所以做個標記,下次就不要到處找了。

  我們可以通php的變數來獲得url和要傳的參數字串:

  $_SERVER["QUERY_STRING"] name=tank&sex=1

  $_SERVER["REQUEST_URI"] /index.php?name=tank&sex=1

  注意:這裡不能擷取錨點的值,比如index.php?p=12#foot,這裡的#foot是不能擷取的,所以在傳遞錨點的值的時候需要使用JS的window.location.hash和window.location.href。

  javascript也可以獲得來源的url,document.referrer;方法有很多。

  1、利用pathinfo:

<?    $test = pathinfo("http://localhost/index.php");    print_r($test);?>結果如下Array( [dirname] => http://localhost //url的路徑 [basename] => index.php //完整檔案名稱 [extension] => php //檔案名稱尾碼 [filename] => index //檔案名稱)

 

  2、利用parse_url()函數解析

 

<?    $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 //後面根的錨點)

 

 

  3、使用basename()

 

<?    $test = basename("http://localhost/index.php?name=tank&sex=1#top");    echo $test;?>結果如下index.php?name=tank&sex=1#top

 

  4、Regex(不建議用,略過)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.