I am trying to login to a form which has a hidden hash field. The problem is when I curl the page to get the hash, and when I include it as the post value in my next curl call (to the same page), the hash is not valid anymore since the succeeding curl cal is like the page refreshed already and it regenerated a new hash.
So how do I get the hash without simulating a refreshed page?
here is my sample code:
<?php
$la = new LoginAuth('http://site.tld/auth.php', 'username', 'password');
$result = $la->auth(0);
echo $result;
class LoginAuth
{
public $url;
public $usr;
public $pwd;
public $status;
private $last_url;
public function __construct($url, $usr, $pwd)
{
$this->url = $url;
$this->usr= $usr;
$this->pwd= $pwd;
}
public function get_hash()
{
$output = $this->curl($this->url, $this->last_url);
$hash = $this->match('!<input.*?name="hash".*?value="(.*?)"!ms', $output, 1);
return $hash;
}
public function auth($server)
{
$hash = $this->get_hash();
$auth_data = 'username=' . $this->usr . '&password=' . $this->pwd . '&server=' . $server . '&hash=' . $hash;
$output = $this->curl($this->url, $this->last_url, $auth_data);
$this->status = $output;
return $output;
}
private function curl($url, $referer = null, $post_param = null)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5H11 Safari/525.20");
if($referer)
curl_setopt($ch, CURLOPT_REFERER, $referer);
if(!is_null($post_param))
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_param);
}
$html = curl_exec($ch);
$this->last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
return $html;
}
private function match($regex, $str, $out_ary = 0)
{
return preg_match($regex, $str, $match) == 1 ? $match[$out_ary] : false;
}
}
/* End of file auth.php */
/* Location: ./auth.php */
The server is probably sending you a Set-Cookie header for a session id. It will store the hash someplace locally, and then compare the one you submit to that one IF you supply the session cookie back to it.
You’ll need to read the session cookie out of the
get_hash()response, and then submit it back in yourauth()call.I’d fire up firebug and check out the headers being sent back and forth when you do it by hand, there may be some other important ones as well.