打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
PHP如何获取短网址跳转之前的网址?

现在有很多的短网址应用,点击就跳转到缩短之前的网址了,那今天我们就来看一下,PHP如何获取短网址跳转之前的网址,其实也很简单,就是用php的get_headers 函数,取得Response Headers,之后慢慢分析就行了。

给出具体实现方法,代码如下:

<?php

$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;

}

?>

实例二,代码如下:

<?php

echo get_redirect_url('https://www.bz80.com/');

//输出结果类似的为:https://www.bz80.com/novel/22505.html

function get_redirect_url($url) {

    $redirect_url = null;

    $url_parts = @parse_url($url);

    if (!$url_parts) return false;

    if (!isset($url_parts['host'])) return false; //can't process relative URLs

    if (!isset($url_parts['path'])) $url_parts['path'] = '/';

    $sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80) , $errno, $errstr, 30);

    if (!$sock) return false;

    $request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?' . $url_parts['query'] : '') . " HTTP/1.1rn";

    $request.= 'Host: ' . $url_parts['host'] . "rn";

    $request.= "Connection: Closernrn";

    fwrite($sock, $request);

    $response = '';

    while (!feof($sock)) $response.= fread($sock, 8192);

    fclose($sock);

    if (preg_match('/^Location: (.+?)$/m', $response, $matches)) {

        if (substr($matches[1], 0, 1) == "/") return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);

        else return trim($matches[1]);

    } else {

        return false;

    }

}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
php获取远程图片的两种 CURL方式和sockets方式获取远程图片
如何用PHP语言制作视频源代理
php 首页自动选择语言跳转的简单示例
!!!!! php 使用curl模拟登录discuz以及模拟发帖 | SimonLeung's Blo...
php 301转向的简单跳转
微信小程序https请求wx.request详细教程
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服