一个站点需要登录三个变量:用户名、密码和令牌。此数据通过 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);
}