您的位置:首页 > 编程语言 > PHP开发

php 解析url 和parse_url使用

2013-08-09 15:14 1001 查看
通过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

javascript也可以获得来源的url,document.referrer;方法有很多

利用pathinfo

<?php
$test = pathinfo("http://localhost/index.php");
print_r($test);
?>
结果如下
Array
(
[dirname] => http://localhost //url的路径
[basename] => index.php  //完整文件名
[extension] => php  //文件名后缀
[filename] => index //文件名
)


利用basename:

<?php

$test = basename("http://localhost/index.php?name=tank&sex=1#top");

echo $test;

?>

结果如下

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

php提供了一个强大的函数,parse_url,来专门解析url:

mixed parse_url ( string
$url
[, int
$component
= -1 ] ) 返回一个关联数组。
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

部分url也可以接受。

component


Specify one of
PHP_URL_SCHEME
,
PHP_URL_HOST
,
PHP_URL_PORT
,
PHP_URL_USER
,
PHP_URL_PASS
,
PHP_URL_PATH
,
PHP_URL_QUERY
or
PHP_URL_FRAGMENT
to retrieve just a specific URL component as a string (except when
PHP_URL_PORT
is given, in which case the return value will be an integer).

最常用的的选项是PHP_URL_PATH,返回路径。

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>


Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: