Пример #1
0
 public function new_shorten_url($long_url = "")
 {
     if (!empty($long_url)) {
         App::import("Model", "ShortUrl");
         $model = new ShortUrl();
         $long_url_array = $model->find('first', array('conditions' => array('ShortUrl.long_url' => $long_url)));
         if ($long_url_array && count($long_url_array) > 0) {
             //$this->set('SHORT_URL', $long_url_array['ShortUrl']['short_url']);
             return $long_url_array['ShortUrl']['short_url'];
         }
         $apiKey = '926968577661';
         $postData = array('longUrl' => $long_url, 'key' => $apiKey);
         $jsonData = json_encode($postData);
         $curlObj = curl_init();
         curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
         curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($curlObj, CURLOPT_HEADER, 0);
         curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
         curl_setopt($curlObj, CURLOPT_POST, 1);
         curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
         $response = curl_exec($curlObj);
         // Change the response json string to object
         $json = json_decode($response);
         curl_close($curlObj);
         if ($json->id) {
             $shortUrlArray = array();
             $shortUrlArray['ShortUrl']['short_url'] = $json->id;
             $shortUrlArray['ShortUrl']['long_url'] = $long_url;
             $model->save($shortUrlArray);
             //$this->set('SHORT_URL', $json->id);
             return $json->id;
         }
         //$this->set('SHORT_URL', $long_url);*/
         return $long_url;
     }
     return '';
 }