15 February, 2011

Login to Hyves using cURL

Logging in to hyves using the API provided by them are great, but i had a different situation where i needed to login to hyves using curl. For this i googled through
but could not get any resources. So i thought of creating it on my own.

The code connects to hyves with curl. Its simple, we just need to use appropriate curl options getting hidden field name::value pairs from the hyves login page along with the form action. And we are done.

So here's the code.

//function to get hidden field name:value pairs from html page
function getHidden($formAsString) {
$hidEles="";
$doc=new DOMDocument();
$doc->loadHTML($string_bulk);
$xpath=new DOMXPath($doc);
$query="//input[@type='hidden']";
$hidData=$xpath->query($query);
foreach($hidData as $field) {
//type cast the value to string
$name=(string) $field->getAttribute('name');
$value=(string) $field->getAttribute('value');
$hidEles[$name]=$value;
}
return $hidEles;
}
//hyves mobile page url for login
$hyvesUrl = "http://www.hyves.nl/mini/?l1=mo";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $hyvesUrl);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPGET ,true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_REFERER, '');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$homepage = curl_exec($ch);

//get the action value of the login form
$searchStr = "/class=\"form\" action=\"(.*?)\"/";
preg_match($searchStr, $page, $matches);
$frmAction = $matches[1];

//get the hidden field name:value pairs from login page
$eles=getHiddenElements($homepage);
$eles['auth_username']="hyves-username";
$eles['auth_password']="hyves-password";
$eles['login']='Login';

//prepare post values
$els='';
$flag = false;
foreach ($eles as $name=>$value) {
if ($flag)
$els.='&';
$els.="{$name}=".urlencode($value);
$flag = true;
}

//now post the login form
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $form_action);
curl_setopt($ch, CURLOPT_POSTFIELDS,$els);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resLogin = curl_exec($ch);
echo $resLogin;
//and you are loggedin

So, in this way you can login to hyves using curl, and after logging in you can do
lots of other stuffs, like add new tips, blogs, send message, etc.

No comments: