如果可以使用php curl自动登录脚本,我需要一些帮助。
我正在处理一个项目,其中一个问题是我需要登录:http://www.marketbook.co.uk并废弃一些信息,但只能登录。
如果您可以节省一些时间,请查看我的代码并告诉我出了什么问题:
<?php
// options
$USER = 'userrrrrrrr';
$PASSWORD = 'passsssssss';
$cookie_file_path = "cookies.txt";
$LOGINURL = "http://www.marketbook.co.uk/Homepage/Default.aspx";
$agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
// begin script
$ch = curl_init();
// extra headers
$headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Host: www.marketbook.co.uk";
$headers[] = "Content-Length: 246";
$headers[] = "Cache-Control: max-age=0";
$headers[] = "Origin: http://www.marketbook.co.uk";
$headers[] = "Upgrade-Insecure-Requests: 1";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Referer: http://www.marketbook.co.uk/homepage/default.aspx?";
$headers[] = "Accept-Encoding: gzip, deflate";
$headers[] = "Accept-Language: en-US,en;q=0.8";
// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
// execute session to get cookies and required form inputs
$content = curl_exec($ch);
// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['__VIEWSTATE'] = $viewstate;
$fields['__VIEWSTATEGENERATOR'] = $viewstategen;
$fields['__EVENTVALIDATION'] = $eventval;
$fields['txtUName'] = $USER;
$fields['txtUPass'] = $PASSWORD;
// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
// perform login
$result = curl_exec($ch);
print $result;
function getFormFields($data)
{
if (preg_match('/(<form action="op.*?<\/form>)/is', $data, $matches)) {
$inputs = getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}