PDA

Просмотр полной версии : [Q] Автоматическое получение Google Map API ключа (php)


draliokero
17.03.2009, 14:24
Здравствуйте, собственно сабж интересует. Как с помощью file_get_contents получить для текущего хоста API key со страницы http://www.google.com/maps/api_signup?url=http%3A%2F%2Fexample.ru

Из-за редиректов через заголовки трабла. Что касается авторизации в Google Accounts нарыл http://code.google.com/intl/ru/apis/accounts/docs/AuthForInstalledApps.html

Буду очень благодарен, если найдется человек, который поможет с кодом

Shadow_p1raT
18.03.2009, 17:42
Это тебе в раздел О работе.
Но так как мне делать было нечего,решил написать...
Скрипт требует модуль php_openssl!

<?php
#########################################
#
# Google Maps Api by Shadow_p1raT
# ICQ#: 9930875
#
#########################################
# #
$email = 'blablabal@gmail.com'; // Аккунт на гмаил.ком
$pass = 'antichat'; // Пароль от акка
$proxy = '127.0.0.1:3130'; // Прокси если надо
$url = 'http://forum.antichat.ru/'; // Урл сайта

# #
echo '<title>Google Maps Api by Shadow_p1raT</title>';
set_time_limit(0);
class gMapKey {

private $email;
private $pass;
private $proxy;
private $url;


private function sock_do($action,$method,$header = false,$params = false,$cookie = false,$referer = false)
{
$out = array('http' => array());
$method = strtoupper($method);
if($method == 'GET') {
$action .= !empty($params) ? '?'.$params : '';
$out['http']['method'] = 'GET';

} elseif($method == 'POST') {
$out['http']['method'] = 'POST';
$out['http']['header'] = "Content-type: application/x-www-form-urlencoded\r\n".
"Content-length: ".strlen($params)."\r\n";
$out['http']['content'] = $params;
} else {
die('Йа криветко');
}
if($this->proxy) {
$out['http']['proxy'] = 'tcp://'.$this->proxy;
}
if($cookie) {
$out['http']['header'] .= 'Cookie: '.$cookie."\r\n";
}
if($referer) {
$out['http']['header'] .= 'Referer: '.$referer."\r\n";
}
$out['http']['header'] .= "Connection: close\r\n";
$out['http']['header'] .= "User-Agent: Opera/9.62 (Windows NT 6.0; U; ru) Presto/2.1.1\r\n";

$content = stream_context_create($out);
$result = @file_get_contents($action,false,$content);
$res = array();
$res = array($result);
if($header) {
$res[] = implode("\r\n",$http_response_header);
}
return $res; //Возвращаем ответ + заголовки
}
private function preg_Cookie($cookie)
{
preg_match_all('#Set-cookie: (.*;)#UiS',$cookie,$headers);
return implode(' ',$headers['1']);
}
private function preg_Location($text)
{
preg_match('#Location: (.*)#',$text,$reg);
return trim($reg['1']);
}
private function getnormal ($str)
{
return str_replace ("&amp;", "&", $str);
}
public function setOption($email,$pass,$url,$proxy = '')
{
$this->email = urlencode($email);
$this->pass = urlencode($pass);
$this->url = urlencode($url);
$this->proxy = $proxy;
}
public function Sign()
{
$res = $this->sock_do('https://www.google.com/accounts/LoginAuth','POST',1,'Email='.$this->email.'&Passwd='.$this->pass.'&PersistentCookie=yes&rmShown=1&signIn=%D0%92%D0%BE%D0%B9%D1%82%D0%B8&asts=');
$cookie = $this->preg_Cookie($res[1]);
$location = $this->preg_Location($res[1]) or die('[-] Неправильный логин или пароль!');
unset($res);
$res = $this->sock_do($location,'GET',1,'',$cookie);
preg_match('~url=\'(.*)'~',$res[0],$reg) or die('[-] Произошла ошибка при логине аккунта!');
$location = $this->getnormal($reg[1]);
unset($res);
$res = $this->sock_do($location,'GET',1,'',$cookie);
$cookie = $this->preg_Cookie($res[1]);
unset($res);
$res = $this->sock_do('http://maps.google.com/maps/api_signup?url='.$this->url,'GET',1,'',$cookie);
if(strstr($res[0],'Your key is'))
{
preg_match('~page_title">(.*)\&copy;2008 Google~sUi',$res[0],$reg);
echo '<html>
<head>
<link href="http://code.google.com/css/codesite.pack.01312008.css" type="text/css" rel="stylesheet"></link>
</head>';
echo $reg[1];
}
else
{
echo '[-] Не удалось получить Google Maps API Key!';
}
}
unset($res);
}
$gmk = new gMapKey();
$gmk->setOption($email,$pass,$url,$proxy);
$gmk->Sign();
?>

Кстати,а почему именно с помощью file_get_contents(),ведь он работает медленнее сокетов и cURL?

P.S Наконецто испытал свою функцию в боевых условиях,выявилось несколько изъянов....

draliokero
19.03.2009, 03:00
Shadow_p1raT, большое Вам спасибо за вашу помощь и реализацию!
Про скорость работы в курсе, для наглядности file_get_contents() хотелось увидеть.

>Это тебе в раздел О работе
Ok, на будущие учту

Shadow_p1raT
19.03.2009, 05:52
>Это тебе в раздел О работе
Ok, на будущие учту
Не обязательно,если скрипт не большой,найдутся люди которые помогут за спасибо.