PHP获取重定向URL的方法是什么

发布时间:2021-12-07 09:35:35 作者:iii
来源:亿速云 阅读:300

本篇内容介绍了“PHP获取重定向URL的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

PHP获取重定向URL的方法:1、使用get_headers函数来获取,语法“get_headers($url, 1)”;2、使用fsockopen()函数来获取;3、利用curl_init()、curl_setopt()等函数来获取。

PHP获取重定向URL的方法是什么

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

1、使用get_headers函数
php自带的get_headers函数可以获取服务器响应一个HTTP请求所发送的所有标头,我们可以尝试用该函数实现。

function get_redirect_url($url){
   $header = get_headers($url, 1);
   if (strpos($header[0], ’301′) !== false || strpos($header[0], ’302′) !== false) {
     if(is_array($header['Location'])) {
       return $header['Location'][count($header['Location'])-1];
     }else{
       return $header['Location'];
        }
   }else {
     return $url;
   }
 }

2、使用fsockopen()内置函数

function get_redirect_url($url){
   $redirect_url = false;
   $url_parts = @parse_url($url);
   if (!$url_parts) return false;
   if (!isset($url_parts['host'])) return false;
   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)){
     return trim($matches[1]);
   } else {
    return false;
  }
}

3、使用cURL函数

function get_redirect_url($url, $referer=”, $timeout = 10) {
   $redirect_url = false;
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_HEADER, TRUE);
   curl_setopt($ch, CURLOPT_NOBODY, TRUE);//不返回请求体内容
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);//允许请求的链接跳转
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      ‘Accept: */*’,
      ‘User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)’,
      ‘Connection: Keep-Alive’));
   if ($referer) {
     curl_setopt($ch, CURLOPT_REFERER, $referer);//设置referer
   }
   $content = curl_exec($ch);
   if(!curl_errno($ch)) {
     $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);//获取最终请求的url地址
   }
   return $redirect_url;
}


“PHP获取重定向URL的方法是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. php中如何实现url重定向
  2. php获取url地址的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php url

上一篇:SRM供应商关系管理系统的解决方案是什么

下一篇:Hyperledger fabric Chaincode开发的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》