2013-03-02 39 views
0

一個站點需要登錄三個變量:用戶名,密碼和令牌。這些數據通過POST發送。使用file_get_contents進行登錄後 - 不捲曲

令牌也通過一個部分發送。

我有所有三個變量,我想通過file_get_contents登錄。

如何發送該數據並驗證成功?

function file_post_contents() 
{ 

    $url = 'http://site.com/auth.php?' . session_name() . '=' . session_id(); 

    $login = 'jhon'; 
    $senha = 'doe'; 

    $token = '123456'; 
    $_SESSION["token"] = $token; 

    $postdata = http_build_query(
     array(
      'login' => $login, 
      'senha' => $senha, 
      'token' => $token, 
          $_SESSION["token"] => $token 
     ) 
    ); 

    $opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => 'Content-type: application/x-www-form-urlencoded', 
      'content' => $postdata 
     ) 
    ); 

    if($login && $senha) 
    { 
     $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$login:$senha")); 
    } 

    $context = stream_context_create($opts); 
    return file_get_contents($url, false, $context); 
} 

修改後的代碼。這是行不通的。

function file_post_contents() 
{ 

    $url = 'http://site.com/auth.php?' . session_name() . '=' . session_id(); 

    $login = 'jhon'; 
    $senha = 'doe'; 

    $token = '123456'; 
    $_SESSION["token"] = $token; 

    $postdata = http_build_query(
     array(
      'login' => $login, 
      'senha' => $senha, 
      'token' => $token 
      //, $_SESSION["token"] => $token 
     ) 
    ); 

    $opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => 'Content-type: application/x-www-form-urlencoded' 
      . "\r\n" . "Authorization: Basic " . base64_encode("$login:$senha"). "\r\n", 
      'content' => $postdata 
     ) 
    ); 


    $context = stream_context_create($opts); 
    return file_get_contents($url, false, $context); 
} 
+0

這是什麼回報給你?它看起來是正確的... – gmaliar 2013-03-02 18:56:08

+0

是的,它看起來是正確的,但返回它無法連接的錯誤消息。 – Guttemberg 2013-03-02 19:07:35

+0

你能發佈錯誤嗎? – gmaliar 2013-03-02 19:08:10

回答

0

你的頭可以被設置錯誤,嘗試添加\r\n像這樣

$opts = array('http' => 
     array(
      'method' => 'POST', 
      'header' => "Content-type: application/x-www-form-urlencoded\r\n", 
      'content' => $postdata 
     ) 
    ); 

,後來下來你與基本認證覆蓋$opts['http']['header']代碼

$opts['http']['header'] = $opts['http']['header'] . "Authorization: Basic " . base64_encode("$login:$senha") . "\r\n";

+0

看來問題出在數據傳輸會話中。 在不創建會話的情況下使用file_get_content之前,顯示了相同的錯誤。 所以我創建了會話並設法執行身份驗證。 現在,使用file_get_content來通知錯誤消息。所以看起來問題是在使用file_get_contents時發送會話數據。 – Guttemberg 2013-03-02 19:53:48

0

。您不會將其添加到Content-type,您將用它替換Content-type。