PHP 117
Lấy URL đích sau khi chuyển hướng 301/302 By Code on 23rd August 2019 12:04:08 PM
  1. <?php
  2.  
  3. // FOLLOW A SINGLE REDIRECT:
  4. // This makes a single request and reads the "Location" header to determine the
  5. // destination. It doesn't check if that location is valid or not.
  6. function get_redirect_target($url)
  7. {
  8.     $ch = curl_init($url);
  9.     curl_setopt($ch, CURLOPT_HEADER, 1);
  10.     curl_setopt($ch, CURLOPT_NOBODY, 1);
  11.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  12.     $headers = curl_exec($ch);
  13.     curl_close($ch);
  14.  
  15.     // Check if there's a Location: header (redirect)
  16.     if (preg_match('/^Location: (.+)$/im', $headers, $matches))
  17.         return trim($matches[1]);
  18.  
  19.     // If not, there was no redirect so return the original URL
  20.     // (Alternatively change this to return false)
  21.     return $url;
  22. }
  23.  
  24. // FOLLOW ALL REDIRECTS:
  25. // This makes multiple requests, following each redirect until it reaches the
  26. // final destination.
  27. function get_redirect_final_target($url)
  28. {
  29.     $ch = curl_init($url);
  30.     curl_setopt($ch, CURLOPT_NOBODY, 1);
  31.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
  32.     curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
  33.     curl_exec($ch);
  34.     $target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  35.     curl_close($ch);
  36.  
  37.     if ($target)
  38.         return $target;
  39.  
  40.     return false;
  41. }
  42.  
  43. // CURLOPT_FOLLOWLOCATION  là đệ quy nên muốn dừng vòng lặp vô tận bằng số lặp cụ thể bằng cách thêm: curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  44. // Như trên là chuyển hướng 3 lần là dừng.

PasteBin.Win is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.