这是我根据您的代码创建的一个有效示例。这使用了
getFormFields我针对类似问题(此文章底部的第一个参考)编写的函数,该函数已登录Android市场。
我认为您的脚本中可能有几件事阻止了登录工作。首先,您应该在帖子字符串中使用网址代码(例如,电子邮件和密码)对URL参数进行编码(cURL不会帮您完成此操作)。其次,我认为
x可能需要用作登录URL一部分的值。
这是成功登录的解决方案。请注意,我重新使用了原始的cURL句柄。这不是必需的,但是如果您指定keep-
alive,它实际上将重用相同的连接,并且还使您不必重复指定相同的选项。
获得cookie后,您可以创建一个新的cURL对象并指定cookieFILE和cookieJAR,您将无需执行第一步即可登录。
<?php// options$EMAIL = 'you@yoursite.com';$PASSWORD = 'yourpassword';$cookie_file_path = "/tmp/cookies.txt";$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; $agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";// begin script$ch = curl_init();// extra headers$headers[] = "Accept: */*";$headers[] = "Connection: Keep-Alive";// basic curl options for all requestscurl_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 URLcurl_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['emailAddress'] = $EMAIL;$fields['acctPassword'] = $PASSWORD;// get x value that is used in the login url$x = '';if (preg_match('/op.asp?x=(d+)/i', $content, $match)) { $x = $match[1];}//$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; $LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?x=$x";// set postfields using what we extracted from the form$POSTFIELDS = http_build_query($fields);// change URL to login URLcurl_setopt($ch, CURLOPT_URL, $LOGINURL);// set post optionscurl_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;}这对我有用,希望对您有所帮助。



