您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/4/21 20:26:54发布9次查看
php获取重定向url的方法:1、使用get_headers函数来获取,语法“get_headers($url, 1)”;2、使用fsockopen()函数来获取;3、利用curl_init()、curl_setopt()等函数来获取。
本教程操作环境: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视频教程》
以上就是php获取重定向url的几种方法是什么的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product