继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

PHP获取动态跳转后的真实链接

函数式编程
关注TA
已关注
手记 220
粉丝 14
获赞 30

网站的跳转链接经常为本站链接加上一些参数来跳转,如何使用php获取跳转后的链接呢?
php代码如下:

<?php

    //echo get_redirect_url('http://www.oschina.net/action/project/go?id=1089&p=home');//输出结果为:http://code.google.com/android/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.1\r\n"; 

    $request .= 'Host: ' . $url_parts['host'] . "\r\n"; 

    $request .= "Connection: Close\r\n\r\n"; 

    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,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP