PHP获取重定向URL的几种方法是什么
2021-12-06 19:39:50
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.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)){ 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的几种方法是什么的详细内容,更多请关注dnjidi.com其它相关文章!
相关阅读
- php ini?set 不起作用怎么办
- php怎么删除mysql行
- php怎么替换某一行内容
- expose?php不起作用怎么办
- 详细介绍php中的Data Structures扩展
- 链表有没有其他的表现形式?
- PHP中如何将儒略历法的日期转换为儒略日计数
- 如何掌握使用array?push()函数的正确姿势
- php日历之儒略日计数与法国共和历法的日期间如何相互转换
- php日历之儒略日计数如何转换为Unix时间戳
- php日历之格利高里历法的日期与儒略日计数如何相互转换
- PHP和Go如何进行环路链表检测
- php中图是什么?如何才能进行存储?
- php中二进制子串如何进行计数
- php函数之如何创建一个函数?
- php函数之如何用其他方式传递参数?
- php命名空间之如何定义空间?
- php命名空间之子命名空间是什么?