我无法通过curl登录该网站



我不明白我做错了什么。有一个服务站点:https://demo.moneta.ru/login.htm.带有记号的常用形式。我敲页面,保存cookie,从表单中获取令牌。下一个请求我从表单数据中发送到地址。带有cookie和令牌。我得到一张401图。

我检查了所有内容,发送了相同的数据,相同的标题。告诉我,我错过了什么?

$receipt = new Receipt;
$receipt->get_scrf();
echo $receipt->get_auth();
Class Receipt {
private $scrf;
private $login_page_url = 'https://demo.moneta.ru/login.htm';
private $login_action_url = 'https://demo.moneta.ru/login';
private $login = 'LOGIN';
private $password = "PASSWORD";
public function get_auth(){
$headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Encoding: gzip, deflate, br',
'Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control: max-age=0',
'Origin: https://demo.moneta.ru',
'Referer: https://demo.moneta.ru/login.htm',
'Sec-Fetch-Dest: document',
'Sec-Fetch-Mode: navigate',
'Sec-Fetch-Site: same-origin',
'Sec-Fetch-User: ?1',
'Upgrade-Insecure-Requests: 1',
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
'Content-Type: application/x-www-form-urlencoded',
'Connection: keep-alive'
];
$post = [
'state' => $this->scrf,
'target' => 'desktop',
'login' => $this->login,
'password' => $this->password
];
return $this->get_page($this->login_action_url, $post, $headers);
}
public function get_scrf(){
$page_html = $this->get_page($this->login_page_url);
preg_match('/<input type="hidden" name="state" value="([0-9a-z-]+)">/', $page_html, $matches, PREG_OFFSET_CAPTURE);
if(isset($matches[1][0])){
$this->scrf = $matches[1][0];
return $matches[1][0];
}
return null;
}
private function get_page($url, $post=null, $headers=null){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE,  dirname(__FILE__).'/cookie.txt');
curl_setopt($ch, CURLOPT_POST, $post!==null );
if($headers){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if($post){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}

来自浏览器的请求

您有

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

其中CCD_ 1是关联阵列。

文档

如果value是一个数组,则内容类型标头将设置为多部分/表单数据

这不是表单的行为,并且与您明确设置的Content-Type标头冲突:

'Content-Type: application/x-www-form-urlencoded'

尝试将POST数据作为URL编码字符串传递给curl_setopt($ch, CURLOPT_POSTFIELDS, ...

您只需要http_build_query()

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $post ) );

最新更新