php 获取301跳转后真实的url

在php采集中经常遇到有URL 301重定向的情况,如果出现了这样的情况,有可能出现造成未知的结果,因为主机名不一样了。我们的采集中主机名不能用301重定向前的URL,要用重定向之后的URL。

我在以下PHP的例子中介绍下怎么获取301定向后真实的URL,目前我知道有两种方法

1、用get_headers函数;2、用cURL

现介绍利用get_headers() 函数获取http头 php 自带的get_headers()取得服务器响应一个 HTTP 请求所发送的所有标头。 获取301状态肯定没问题。

301定向的例子: google.com 会301跳转至 www.google.com 再www.google.com 会302跳转至 www.google.com.hk

我写了个php函数 其php函数作用: 输入 google.com 得到 www.google.com.hk 输入 www.google.com 得到 www.google.com.hk 输入 www.google.com.hk 得到 www.google.com.hk

<?php /* @param str $url 查询 $return str 定向后的url的真实url */ function getrealurl($url){ $header = get_headers($url,1); if (strpos($header[0],'301') || strpos($header[0],'302')) { if(is_array($header['Location'])) { return $header['Location'][count($header['Location'])-1]; }else{ return $header['Location']; } }else { return $url; } } $url = 'http://google.com'; $url = getrealurl($url); echo '真实的url为:'.$url; //真实的url为:http://www.google.com.hk/ ?>

转载于:https://my.oschina.net/baiduapi/blog/299228

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值