PHP cURL: Get target of redirect, without following it -


the curl_getinfo function returns lot of metadata result of http request. however, reason doesn't include bit of information want @ moment, target url if request returns http redirection code.

i'm not using curlopt_followlocation because want handle specific redirect codes special cases.

if curl can follow redirects, why can't tell me redirect when isn't following them?

of course, set curlopt_header flag , pick out location header. there more efficient way?

this can done in 4 easy steps:

step 1. initialise curl

curl_init($ch); //initialise curl handle //cookiesession optional, use if want keep cookies in memory curl_setopt($this->ch, curlopt_cookiesession, true); 

step 2. headers $url

curl_setopt($ch, curlopt_url, $url); //specify url curl_setopt($ch, curlopt_header, true); //include headers in http data curl_setopt($ch, curlopt_followlocation, false); //don't follow redirects $http_data = curl_exec($ch); //hit $url $curl_info = curl_getinfo($ch); $headers = substr($http_data, 0, $curl_info['header_size']); //split out header 

step 3. check if have correct response code

if (!($curl_info['http_code']>299 && $curl_info['http_code']<309)) {   //return, echo, die, whatever   return 'error - http code'.curl_info['http_code'].' received.'; } 

step 4. parse headers new url

preg_match("!\r\n(?:location|uri): *(.*?) *\r\n!", $headers, $matches); $url = $matches[1]; 

once have new url can repeat steps 2-4 like.


Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -