-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttp-redirect-target.php
36 lines (36 loc) · 1.32 KB
/
http-redirect-target.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
// FOLLOW A SINGLE REDIRECT:
// This makes a single request and reads the "Location" header to determine the
// destination. It doesn't check if that location is valid or not.
//https://gist.github.com/davejamesmiller/dbefa0ff167cc5c08d6d
function get_redirect_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = curl_exec($ch);
curl_close($ch);
// Check if there's a Location: header (redirect)
if (preg_match('/^Location: (.+)$/im', $headers, $matches))
return trim($matches[1]);
// If not, there was no redirect so return the original URL
// (Alternatively change this to return false)
return $url;
}
// FOLLOW ALL REDIRECTS:
// This makes multiple requests, following each redirect until it reaches the
// final destination.
function get_redirect_final_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_exec($ch);
$target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ($target)
return $target;
return false;
}