使用 cURL 和 PHP 以编程方式登录到 SSL 站点


Programmatically log in to SSL site with cURL and PHP

我的警报公司为我提供了一个个人状态页面,我想使用 PHP 和 cURL 以编程方式登录到状态页面以获取一些状态。

但是,登录表单使用CSRF,所以我最初的想法是抓取站点,获取字段值,并使用PHP和cURL提交它们,并将cookie保存在cookie文件中。

据我了解,问题是登录站点使用的是Backbone,并且许多内容都加载了JavaScript。因此,每当我尝试获取数据时,即使我设法登录,我也会被重定向到"选择您的语言"页面。

我尝试登录的页面 https://mypages.verisure.com,这是我目前拥有的代码:

<?php
$username = 'xx@xx.xx';
$password = 'xx';
$loginUrl = 'https://mypages.verisure.com/j_spring_security_check?locale=no_NO';
// init curl
$ch = curl_init();
// set the url to work with
curl_setopt( $ch, CURLOPT_URL, $loginUrl );
// enable http post
curl_setopt( $ch, CURLOPT_POST, 1 );
// set the post parameters
curl_setopt( $ch, CURLOPT_POSTFIELDS, 'j_username=' . $username . '&j_password=' . $password . '&spring-security-redirect=%2Fno%2Fstart.html' );
// handle cookies for the login
curl_setopt( $ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
// execute the request
$store = json_decode( curl_exec( $ch ) );
if ( $store->status == 'ok' )
{
    curl_setopt( $ch, CURLOPT_URL, 'https://mypages.verisure.com' . $store->redirectUrl );
    $content = curl_exec( $ch );
    var_dump( $content );
}
?>

$store变量包含以下内容:

{
    "status": "ok",
    "redirectUrl": "/no/start.html",
    "message": null
}

您对如何登录使用SSL和JavaScript的网站有任何提示吗?

如果需要JavaScript,cURL和PHP可能不是正确的工具。你可以试试PhantomJS,这是一个基于Webkit的无头浏览器,即使涉及JavaScript,也可以用来自动与网站交互。