0

一个站点需要登录三个变量:用户名、密码和令牌。此数据通过 POST 发送。

令牌也通过一个部分发送。

我拥有所有三个变量,我想通过 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);
}
4

2 回答 2

0

您正在$opts['http']['header']使用基本身份验证进行覆盖。您没有将其添加到 Content-type 中,而是将 Content-type 替换为它。

于 2013-03-02T19:32:13.987 回答
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'] . "Authorization: Basic " . base64_encode("$login:$senha") . "\r\n";

于 2013-03-02T19:27:08.160 回答