• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

php解析url和parse_url使用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

通过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:

  1. <?php  
  2. $test = basename("http://localhost/index.php?name=tank&sex=1#top");  
  3. echo $test;  
  4. ?>  
  5. 结果如下  
  6. 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_SCHEMEPHP_URL_HOSTPHP_URL_PORTPHP_URL_USERPHP_URL_PASSPHP_URL_PATHPHP_URL_QUERY orPHP_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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHPFunction参数传递发布时间:2022-07-10
下一篇:
精选国外免费PHP空间推荐发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap