Handling Redirects with PHP/CURL

June 29th, 2009 by admin Leave a reply »

Ever wanted to see all the different redirect urls a particular link redirects through with PHP/CURL? Now you can with this nifty little piece of code (the only thing I haven’t written yet is a way to handle redirects that don’t contain the hostname). Anyway, with that said, check this out:

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
$url = "http://www.somesiteyouknowuseslocationredirect.com";
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_URL, $url);
 
$data = curl_exec($ch);
 
$curl_info = curl_getinfo($ch);
 
$redirect_count = $curl_info['redirect_count'];
 
$header_size = $curl_info['header_size'];
 
$header = substr($data, 0, $header_size);
 
$redirecturls = array();
 
if($redirect_count>0){
 
preg_match_all("/location:(.*?)\n/is", $header, $locations);
 
foreach($locations[1] as $location){;
$redirecturls[] = trim($location);
}
 
}
Advertisement

Leave a Reply