在重构之前检测 url 是否正在重定向


Detect if the url is redirecting before iframing it

>我正在构建一个应用程序,但我在某个时候被困住了,我有一个 iframe,它的源代码是根据以下条件动态确定的:

<?php
ini_set('display_errors','off');
$file = $_GET['file'];
$url = ('remotedomain. com/' .$file);
?>

现在这里是iframe:

<iframe id="embed" src="<? echo $url; ?>"></iframe>

我卡在的一点是有时 URL(即 iframe 源(重定向回主页,我想检测此重定向,如果会发生,那么 iframe 的来源应该是某个 URL,例如我的网站 .com/page1.html

使用 curl 和选项 CURLOPT_HEADER。它是这样的:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); //your url
curl_setopt($CURL, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (preg_match('#HTTP.{4} 30[34]#m', $result)) {
    if (preg_match('#'vLocation: (.*)'v#m', $result, $matches)) {
        echo "Found redirect: ", $matches[1], "'n";
    }
}

您可以改用Guzzle,它将遵循重定向。

$response = $client->get('http://github.com');
echo $response->getStatusCode();
// 200
echo $response->getEffectiveUrl();
// 'https://github.com/'

getEffectiveUrl((; 将在此处打印它重定向到的位置。

像这样:

function getFinalUrl($url) //in your library 
{
    $client = new GuzzleHttp'Client();
    $response = $client->get($url);
    if (in_array($response->getStatusCode(), [303, 304], true)) {
        $url = $response->getEffectiveUrl();
    }
    return $url;
}

和 iframe:

<iframe id="embed" src="<?=getFinalUrl($url);?>"></iframe>

感谢每一个与我讨论这个问题的人,我设法做到了,这是答案,所以如果有人需要它:

$url = (remote site .com/' .$file);
$start_time = microtime(TRUE);
$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_NOBODY, 1);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 302) {
$final_url = 'mysite .com/page1.php';
}
 else {
 $final_url = $url;
 } 

您可以使用以下 javascript 查找 iframe 的当前 URL:

document.getElementById("iframe_id").contentWindow.location.href

您可以将此网址与要避免的主页的网址进行比较。如果匹配,请将其重定向到您的备用网址