Este sitio web utiliza cookies para realizar análisis y mediciones de tus visitas. [ Acepto ] [ Más información aquí ].

How to Detect a 301 Redirect in PHP

To detect a 301 redirect from a domain to another, just use the following PHP code. For this example we'll use www.obrasocialcajamadrid.es, which redirects to www.fundacionmontemadrid.es. Replace it with the URL you prefer:

$url = "www.obrasocialcajamadrid.es";

function detect_redirect ($url) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_URL, $url);

$out = curl_exec($ch);

$out = str_replace("\r", "", $out);

$headers_end = strpos($out, "\n\n");

if( $headers_end !== false ) {

$out = substr($out, 0, $headers_end);

}

$headers = explode("\n", $out);

foreach($headers as $header) {

if( substr($header, 0, 10) == "Location: " ) {

$target = substr($header, 10);

$pieces = explode("?", $target);

}

}

return $pieces[0];

}

$result = detect_redirect($url);

echo $result;

Añadir comentario