当前位置:Gxlcms > PHP教程 > php怎么获取跳转后的url?

php怎么获取跳转后的url?

时间:2021-07-01 10:21:17 帮助过:57人阅读

php获取跳转url的方法:1、使用get_headers函数获取跳转后的url,该函数可以获取服务器响应一个HTTP请求所发送的所有标头;2、使用fsockopen()函数;3、使用使用cURL函数。

推荐:《PHP视频教程》

有时候我们会在开发中,经常会遇到有URL 301或 302重定向的情况,这时候我们可能需要获取重定向之后的url,下面我们介绍一下几种获取重定向url的方法:

1、用get_headers函数

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

  1. function get_redirect_url($url){
  2. $header = get_headers($url, 1);
  3. if (strpos($header[0], ’301′) !== false || strpos($header[0], ’302′) !== false) {
  4. if(is_array($header['Location'])) {
  5. return $header['Location'][count($header['Location'])-1];
  6. }else{
  7. return $header['Location'];
  8. }
  9. }else {
  10. return $url;
  11. }
  12. }

2、使用fsockopen()内置函数

  1. function get_redirect_url($url){
  2. $redirect_url = false;
  3. $url_parts = @parse_url($url);
  4. if (!$url_parts) return false;
  5. if (!isset($url_parts['host'])) return false;
  6. if (!isset($url_parts['path'])) $url_parts['path'] = ‘/’;
  7. $sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
  8. if (!$sock) return false;
  9. $request = “HEAD ” . $url_parts['path'] . (isset($url_parts['query']) ? ‘?’.$url_parts['query'] : ”) . ” HTTP/1.1\r\n”;
  10. $request .= ‘Host: ‘ . $url_parts['host'] . “\r\n”;
  11. $request .= “Connection: Close\r\n\r\n”;
  12. fwrite($sock, $request);
  13. $response = ”;
  14. while(!feof($sock)) $response .= fread($sock, 8192);
  15. fclose($sock);
  16. if (preg_match(‘/^Location: (.+?)$/m’, $response, $matches)){
  17. return trim($matches[1]);
  18. } else {
  19. return false;
  20. }
  21. }

3、使用cURL函数

  1. function get_redirect_url($url, $referer=”, $timeout = 10) {
  2. $redirect_url = false;
  3. $ch = curl_init();
  4. curl_setopt($ch, CURLOPT_URL, $url);
  5. curl_setopt($ch, CURLOPT_HEADER, TRUE);
  6. curl_setopt($ch, CURLOPT_NOBODY, TRUE);//不返回请求体内容
  7. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);//允许请求的链接跳转
  8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  9. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  10. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  11. ‘Accept: */*’,
  12. ‘User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)’,
  13. ‘Connection: Keep-Alive’));
  14. if ($referer) {
  15. curl_setopt($ch, CURLOPT_REFERER, $referer);//设置referer
  16. }
  17. $content = curl_exec($ch);
  18. if(!curl_errno($ch)) {
  19. $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);//获取最终请求的url地址
  20. }
  21. return $redirect_url;
  22. }

哪个方法的效果更高一些,可以自行测试一下。

更多编程相关知识,请访问:编程入门!!

以上就是php怎么获取跳转后的url?的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行