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

Discussion in 'PHP' started by draliokero, 17 Mar 2009.

  1. draliokero

    draliokero Member

    Joined:
    14 Mar 2009
    Messages:
    83
    Likes Received:
    6
    Reputations:
    0
    Здравствуйте, собственно сабж интересует. Как с помощью 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

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

    Shadow_p1raT Elder - Старейшина

    Joined:
    9 Mar 2008
    Messages:
    174
    Likes Received:
    93
    Reputations:
    0
    Это тебе в раздел О работе.
    Но так как мне делать было нечего,решил написать...
    Скрипт требует модуль php_openssl!
    PHP:
    <?php
    #########################################
    #
    #            Google Maps Api by Shadow_p1raT
    #                ICQ#: 9930875
    #
    #########################################
    # [setting] #
    $email 'blablabal@gmail.com'// Аккунт на гмаил.ком
    $pass  'antichat'// Пароль от акка
    $proxy '127.0.0.1:3130'// Прокси если надо
    $url   '/'// Урл сайта 

    #[/setting] #
    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 Наконецто испытал свою функцию в боевых условиях,выявилось несколько изъянов....
     
  3. draliokero

    draliokero Member

    Joined:
    14 Mar 2009
    Messages:
    83
    Likes Received:
    6
    Reputations:
    0
    Shadow_p1raT, большое Вам спасибо за вашу помощь и реализацию!
    Про скорость работы в курсе, для наглядности file_get_contents() хотелось увидеть.

    >Это тебе в раздел О работе
    Ok, на будущие учту
     
    1 person likes this.
  4. Shadow_p1raT

    Shadow_p1raT Elder - Старейшина

    Joined:
    9 Mar 2008
    Messages:
    174
    Likes Received:
    93
    Reputations:
    0
    Не обязательно,если скрипт не большой,найдутся люди которые помогут за спасибо.