Skip to content

Instantly share code, notes, and snippets.

@gonejack
Last active October 31, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonejack/98556f369b6d05edf0ff to your computer and use it in GitHub Desktop.
Save gonejack/98556f369b6d05edf0ff to your computer and use it in GitHub Desktop.
PHP get URL redirect location
<?php
function get_redirect_url($url) {
stream_context_set_default(array(
'http' => array(
#'method' => 'HEAD',
'request_fulluri' => true,
'proxy' => 'tcp://127.0.0.1:1080'
)
));
$headers = @get_headers($url, true);
if ($headers && isset($headers['Location'])) {
return $headers['Location'];
} else {
return false;
}
}
/* curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:1080');*/
function get_redirect_target($url)
{
$ch = curl_init($url);
$options = array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PROXY => '127.0.0.1:1080',
CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',
CURLOPT_HTTPHEADER => array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4'
),
);
curl_setopt_array($ch, $options);
$i = 0;
do {
$headers = curl_exec($ch);
} while (!$headers && $i++ < 3);
curl_close($ch);
if (preg_match('/^Location: (.+)$/im', $headers, $matches)) {
return trim($matches[1]);
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment