2010-06-03 5 views
7

로그인하지 않은 사용자를 제한하려는 각 페이지에서 실행되는 기능을 구현했습니다. 이 함수는 방문자가 로그인하지 않은 경우 로그인 페이지로 방문자를 자동으로 리디렉션합니다.PHP : URL 리디렉션을 확인 하시겠습니까?

외부 서버에서 실행되는 PHP 함수를 만들고 싶습니다. 여러 URL을 반복합니다. 각 보호 된 사이트에 대한 URL이 포함 된 배열)를 사용하여 리디렉션되는지 여부를 확인할 수 있습니다. 따라서 모든 페이지에서 보호 기능이 작동하고 있는지 쉽게 확인할 수 있습니다.

어떻게이 작업을 수행 할 수 있습니까?

감사합니다.

+0

방법 리디렉션을? 어떤 고객에게 전화 했습니까? 로그인했을 때 또는 로그인하지 않았을 때? 무엇 때문에? 스크립트가 세션 쿠키 및 기타 복잡한 작업을 처리해야합니까? –

+0

"리디렉션 된 URL"을 지정하십시오. –

+0

[PHP에서 URL 리디렉션을 어떻게 확인할 수 있습니까?] (http://stackoverflow.com/questions/427203/how-can-i-determine-if-a-url-redirects-in-php/481377#) 481377) –

답변

21
$urls = array(
    'http://www.apple.com/imac', 
    'http://www.google.com/' 
); 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

foreach($urls as $url) { 
    curl_setopt($ch, CURLOPT_URL, $url); 
    $out = curl_exec($ch); 

    // line endings is the wonkiest piece of this whole thing 
    $out = str_replace("\r", "", $out); 

    // only look at the headers 
    $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); 

      echo "[$url] redirects to [$target]<br>"; 
      continue 2; 
     } 
    } 

    echo "[$url] does not redirect<br>"; 
} 
+0

슈퍼 달콤한 솔루션! Tack Adam :) – Industrial

+2

또한 curl_getinfo ($ ch, CURLINFO_HTTP_CODE)를 사용하여 상태 코드 (301 또는 302)를 읽을 수도 있습니다. – baloo

+2

'curl_setopt ($ handle, CURLOPT_NOBODY, true);를 사용하면 대역폭과 처리 능력을 절약 할 수 있습니다. '. 이렇게하면 HTTP HEAD 요청 만 전송됩니다. 이렇게하면 몸을자를 필요가 없습니다. 이 기사를 참조하십시오 : http://schlitt.info/opensource/blog/0606_sending_head_requests_with_extcurl.html – chiborg

-2

질문을 이해할 수 없습니다. URL이 포함 된 배열이 있는데 사용자가 나열된 URL 중 하나인지 알고 싶습니까? 내가 바로 퀘스트를 이해 해요 경우 는 :

$urls = array('http://url1.com','http://url2.ru','http://url3.org'); 
if(in_array($_SERVER['HTTP_REFERER'],$urls)) 
{ 
echo 'FROM ARRAY'; 
} else { 
echo 'NOT FROM ARR'; 
} 
+0

referer가 약함 –

+0

질문이 업데이트되었습니다. 배열에있는 모든 URL을 호출하여 설정된 URL에 머물러 있는지 확인하거나 로그인 페이지로 리디렉션하고 싶습니다. – Industrial

0

당신은 세션을 사용할 수있는 세션 배열이 설정되지 않은 경우, URL은 로그인 페이지로 리디렉션. .

+0

이것이 내 보안이 기본적으로 기반하는 방법이지만 배열의 페이지가 리디렉션되는지 여부를 확인할 수 없습니다. – Industrial

1

보안 확인으로 이것이 실제로 적합한 지 여부는 확실하지 않습니다.

"사용자가 로그인 했습니까?"가 표시되지 않고 파일이 직접 호출되는 것에 대해 걱정이된다면 수표가 실행중인 경우 많은 PHP 프로젝트에서 할 수 있습니다. 중앙 포함 파일 (보안 검사가 수행되는 곳)에서 상수가 설정되었는지 여부를 확인하기 위해 상수를 BOOTSTRAP_LOADED 또는 기타와 모든 파일에서 정의합니다.

테스트가 훌륭하고 보안 테스트가 더 우수하지만이 취약점을 발견하기 위해 어떤 결함이 있는지 확실하지 않습니다. 나에게이 아이디어는 진정한 추가적인 보안을 가져 오지 않는 시간 낭비라고 느낀다.

header("Location:...") 리디렉션 후에 스크립트 die()을 확인하십시오. 리디렉션 헤더가 계속 발행되므로 헤더 명령 다음에 추가 콘텐츠가 표시되는 것을 막는 것이 필수적입니다. (누락 된 다이()는 아이디어로 인해 캐치되지 않습니다.)

정말로 이것을하고 싶다면 wget 같은 도구를 사용하여 URL 목록을 제공 할 수 있습니다. 결과를 디렉토리로 가져 와서 모든 페이지에 로그인 대화 상자가 있는지 여부를 확인합니다 (예 : 동일한 파일 크기를 확인). 다른 옵션을 추가하기 만하면 ...

1

HTTP 코드가 리디렉션인지 확인 하시겠습니까?

$params = array('http' => array(
     'method' => 'HEAD', 
     'ignore_errors' => true 
    )); 

    $context = stream_context_create($params); 
    foreach(array('http://google.com', 'http://stackoverflow.com') as $url) { 
     $fp = fopen($url, 'rb', false, $context); 
     $result = stream_get_contents($fp); 

     if ($result === false) { 
      throw new Exception("Could not read data from {$url}"); 
     } else if (! strstr($http_response_header[0], '301')) { 
      // Do something here 
     } 
    } 
0

나는 Adam Backstrom 대답을 수정하고 chiborg 제안을 구현했습니다. (HEAD 만 다운로드). 한 가지 더 있습니다 : 리디렉션이 동일한 서버의 페이지에 있는지 또는 없는지 확인합니다. 예 : terra.com.br은 terra.com.br/portal로 리디렉션됩니다. PHP는 리다이렉트 (redirect)와 같은 것으로 고려할 것이고, 올바른 것입니다. 하지만 난 단지 다른 URL로 리디렉션하는 URL을 나열하고 싶었어요. 내 영어가 좋지 않습니다. 누군가 이해하기 어려운 것을 발견하고이를 편집 할 수 있다면 환영합니다.(302) 이후

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

가 이동을 의미 컬 호출을 따라 어떤 이동 된 URL의 수익률을 반환 할 수 있습니다 :

function RedirectURL() { 
    $urls = array('http://www.terra.com.br/','http://www.areiaebrita.com.br/'); 

    foreach ($urls as $url) { 
     $ch = curl_init(); 

     curl_setopt($ch, CURLOPT_HEADER, true); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     // chiborg suggestion 
     curl_setopt($ch, CURLOPT_NOBODY, true); 

     // ================================ 
     // READ URL 
     // ================================ 

     curl_setopt($ch, CURLOPT_URL, $url); 
     $out = curl_exec($ch); 

     // line endings is the wonkiest piece of this whole thing 
     $out = str_replace("\r", "", $out); 
     echo $out; 

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

     foreach($headers as $header) { 
      if(substr(strtolower($header), 0, 9) == "location:") { 
       // read URL to check if redirect to somepage on the server or another one. 
       // terra.com.br redirect to terra.com.br/portal. it is valid. 
       // but areiaebrita.com.br redirect to bwnet.com.br, and this is invalid. 
       // what we want is to check if the address continues being terra.com.br or changes. if changes, prints on page. 

       // if contains http, we will check if changes url or not. 
       // some servers, to redirect to a folder available on it, redirect only citting the folder. Example: net11.com.br redirect only to /heiden 

       // only execute if have http on location 
       if (strpos(strtolower($header), "http") !== false) { 
        $address = explode("/", $header); 

        print_r($address); 
        // $address['0'] = http 
        // $address['1'] = 
        // $address['2'] = www.terra.com.br 
        // $address['3'] = portal 

        echo "url (address from array) = " . $url . "<br>"; 
        echo "address[2] = " . $address['2'] . "<br><br>"; 

        // url: terra.com.br 
        // address['2'] = www.terra.com.br 

        // check if string terra.com.br is still available in www.terra.com.br. It indicates that server did not redirect to some page away from here. 
        if(strpos(strtolower($address['2']), strtolower($url)) !== false) { 
         echo "URL NOT REDIRECT"; 
        } else { 
         // not the same. (areiaebrita) 
         echo "SORRY, URL REDIRECT WAS FOUND: " . $url; 
        } 
       } 
      } 
     } 
    } 
} 
0
function unshorten_url($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); 

    $real_url = $url;//default.. (if no redirect) 

    if (preg_match("/location: (.*)/i", $out, $redirect)) 
     $real_url = $redirect[1]; 

    if (strstr($real_url, "bit.ly"))//the redirect is another shortened url 
     $real_url = unshorten_url($real_url); 

    return $real_url; 
} 
2

당신은 항상 추가 시도 할 수 있습니다.

+0

이게 ... 실제로 올바른 대답입니다. 고맙습니다! 이 컬이 없으면 컨텐트는 중단되고 리디렉션이있는 경우 리디렉션을 따르지 않습니다. 고맙습니다!!! –

3

내가 곱슬 곱슬 사용하고 난 헤더 컬에서 내 URL과 URL을 비교 한 후에 만 ​​헤더를 가지고 :

   $url="http://google.com"; 
       $ch = curl_init(); 

       curl_setopt($ch, CURLOPT_URL, $url); 
       curl_setopt($ch, CURLOPT_TIMEOUT, '60'); // in seconds 
       curl_setopt($ch, CURLOPT_HEADER, 1); 
       curl_setopt($ch, CURLOPT_NOBODY, 1); 
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
       $res = curl_exec($ch); 

       if(curl_getinfo($ch)['url'] == $url){ 
        $status = "not redirect"; 
       }else { 
        $status = "redirect"; 
       } 
관련 문제