使用CURL从HTTPS提交表单登录

时间:2017-11-10 23:15:54

标签: php curl

我需要使用POST(asp.net)从外部网站提交一个登录表单,我从这里开始阅读这个主题,而且有几个例子我无法使它工作。

我知道我发送了正确的参数,因为在使用邮递员进行测试时,我得到了家庭HTML的响应,所以我在代码中做错了一定是错的,这就是我&# 39;我现在正在尝试:

// Create temp file to store cookies
$ckfile = tempnam ("/tmp", "CURLCOOKIE");

// URL to login page
$url = "https://site/Login.aspx";

// Get Login page and its cookies and save cookies in the temp file
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);

$fields = array(
'ctl00$ContentPlaceHolder1$txtUser' => 'user',
'ctl00$ContentPlaceHolder1$txtPassword' => '******',
'__VIEWSTATEGENERATOR'=> '716EFC3E',
'__EVENTVALIDATION'=> 'dfsgsdf5463456',
'__LASTFOCUS'=> '',
'__EVENTTARGET'=> '',
'__EVENTARGUMENT'=> '',
'__VIEWSTATE'=> 'wEPDwUKLTM1Mjk0NzM0Mw9kFgJmD2QWAgIDD2QWAgID',
'ctl00$ContentPlaceHolder1$btnLogin'=> 'In',
);

$fields_string = '';
foreach($fields as $key=>$value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');

// Post login form and follow redirects
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // I also try it with false
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
$output = curl_exec($ch);

echo $output;
curl_close($ch);

此输出是一般的服务器运行时错误。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

许多/大多数登录页面使用您需要从登录表单中获取的一次性安全令牌值。

工作流程如下:

  1. 获取登录页面
  2. 从页面回复中抓取(解析,提取)一次性令牌
  3. 使用令牌提交表单
  4. 您的代码看起来像是使用过时的硬编码令牌。