您可以使用PHP cURL浏览和提交表单到网站,但这取决于网站的设置方式。大多数都进行了安全检查以防止机器人出现,并且很难让一切正常工作。
我花了一点时间想出了这个登录脚本。如果没有有效的用户名和密码,我无法验证它是否成功,但应该做你需要的。这个简短的示例首先浏览到页面以设置任何 cookie 并抓取提交表单所需的 __VIEWSTATE 值。然后它使用您提供的用户名/密码提交表单。
<?php
// Login information
$username = 'test';
$password = 'mypass';
$utcoffset = '-6';
$cookiefile = '/writable/directory/for/cookies.txt';
$client = new Client($cookiefile);
// Retrieve page first to store cookies
$page = $client -> get("https://pm.officeally.com/pm/login.aspx");
// scrape __VIEWSTATE value
$start = strpos($page, '__VIEWSTATE" value="') + 20;
$end = strpos($page, '"', $start);
$viewstate = substr($page, $start, $end - $start);
// Do our actual login
$form_data = array(
'__LASTFOCUS' => '',
'__EVENTTARGET' => '',
'__EVENTARGUMENT' => '',
'__VIEWSTATE' => $viewstate,
'hdnUtcOffset' => $utcoffset,
'Login1$UserName' => $username,
'Login1$Password' => $password,
'Login1$LoginButton' => 'Log In'
);
$page = $client -> get("https://pm.officeally.com/pm/login.aspx", $form_data);
// cURL wrapper class
class Login {
private $_cookiefile;
public function __construct($cookiefile) {
if (!is_writable($cookiefile)) {
throw new Exception('Cannot write cookiefile: ' . $cookiefile);
}
$this -> _cookiefile = $cookiefile;
}
public function get($url, $referer = 'http://www.google.com', $data = false) {
// Setup cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this -> _cookiefile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this -> _cookiefile);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
// Is there data to post
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
return curl_exec($ch);
}
}