How to get final URL after following HTTP redirections in pure PHP? -


What do I have to do? What is the last / final URL after following the redirection

I would not like to use curl. I would like to stick with pure PHP (stream wrapper).

I have a URL now (let's say), and I use get_headers () to get specific headers from that page. Get_headers will also return a number of locations: headers (see edit below) to create a final URL, what would be a way to use those headings is? Or is there a PHP function that will do this automatically?

Edit: get_headers () redirections are as follows and returns all the headers for each response / redirection, so I have all the location: headers .

  / ** * get_redirect_url () * receives the address that provides the URL Is *, or wrong if there is no redirect. * * @trust string $ url * return string * / function get_redirect_url ($ url) {$ redirect_url = null; $ Url_parts = @ parse_url ($ url); If (! $ Url_parts) return false; If (! Isset ($ url_parts ['host'])) returned incorrectly; // can not process relative URL if (! Isset ($ url_parts ['path'])) $ url_parts ['path'] = '/'; $ Sock = fsockopen ($ url_parts ['host'], (isset ($ url_parts ['port'])? (Int) $ url_parts ['port']: 80), $ errno, $ errstr, 30); If (! $ Sock) returned false; $ Request = "head" $ Url_parts ['path'] (Isset ($ url_parts ['query'])? '?'. $ Url_parts ['query']: ''). "Http / 1.1 \ r \ n"; $ Request = 'Host:' $ Url_parts ['host']. "\ R \ n"; $ Request = "Connection: Close \ r \ n \ r \ n"; FILIT ($ SOCK, $ REQUEST); $ Reaction = ''; While (.fif ($ sock)) $ reaction = Fread ($ sock, 8192); Fclose ($ sock); Return to $ url_parts if (preg_match ('/ ^ location: (. +?) $ / M', $ response, $ match)) {if (substr ($ matches [1], 0, 1) == "/") ['Scheme'] ": //" $ Url_parts ['host']. Trim ($ matches [1]); And return trim ($ matches [1]); } Other {return false; }} / ** * get_all_redirects () * Takes and collects all the redirects for the given URL. * * @trust string $ url * return array * / function get_all_redirects ($ url) {$ redirects = array (); While ($ newurl = get_redirect_url ($ url)) {if (in_array ($ newurl, $ redirection)) {break; } $ Redirection [] = $ newurl; $ Url = $ newurl; } Return $ Redirect; } / ** * get_final_url () * gets the address that ultimately leads to the URL * if there is no redirection, give $ url yourself * * @The exact string $ url * @ Return string * / function get_final_url ( $ Url) {$ redirects = get_all_redirects ($ url); If (count ($ redirect) & gt; 0) {return_pop ($ redirection); } And {refund $ url; }}  

And as always, give credit:


Comments