Post login with file_get_contents - not curl



一个站点需要登录三个变量:用户名、密码和令牌。这个数据是通过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'
             . "rn" . "Authorization: Basic " . base64_encode("$login:$senha"). "rn",
            'content' => $postdata
        )
    );

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

您的头可能设置错误,尝试添加rn像这样

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

和后面的代码

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

您正在用基本权限覆盖$opts['http']['header']。您不是将它添加到Content-type,而是将它替换为Content-type。

相关内容

  • 没有找到相关文章

最新更新