<?php
/**
* Description of Google_Short_Url_Lib
*
* @author Achi Li
*/
class Google_Short_Url_Lib {
//put your code here
private $api_url, $api_key, $max_retry;
private $CI;
//
public function __construct() {
$this->api_url = "https://www.googleapis.com/urlshortener/v1/url";
$this->api_key = "APP KEY請自行到google 免費申請";
$this->max_retry = 5;
}
public function get_api_url() {
return $this->api_url;
}
public function get_api_key() {
return $this->api_key;
}
public function create_short_url($long_url) {
for ($i = 0; $i < $this->max_retry; $i++) {
$curl_result = $this->curl_short_url($long_url);
$web_info = json_decode($curl_result["web_info"], TRUE);
if (isset($web_info["error"])) {
sleep(2);
} else {
$i = $this->max_retry;
}
}
$google_short_return = array();
$google_short_return["api_url"] = $curl_result["url"];
$google_short_return["http_status"] = $curl_result["http_status"];
$google_short_return["curl_error_no"] = $curl_result["curl_error_no"];
$web_info = json_decode($curl_result["web_info"], TRUE);
if (isset($web_info["error"])) {
$google_short_return["google_status"] = "error";
$google_short_return["google_status_desc"] = $web_info["error"]["errors"][0]["message"];
$google_short_return["google_short_url"] = "";
} else {
$google_short_return["google_status"] = "success";
$google_short_return["google_status_desc"] = "success";
$google_short_return["google_short_url"] = $web_info["id"];
}
return $google_short_return;
}
public function curl_short_url($long_url) {
$apiKey = $this->get_api_key();
$postData = array('longUrl' => $long_url, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
$api_url = $this->get_api_url() . "?key=" . $apiKey;
curl_setopt($curlObj, CURLOPT_URL, $api_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);
$result = curl_exec($curlObj);
$retcode = curl_getinfo($curlObj, CURLINFO_HTTP_CODE);
$curl_error = curl_errno($curlObj);
curl_close($curlObj);
$return_info = array(
"url" => $api_url,
"http_status" => $retcode,
"curl_error_no" => $curl_error,
"web_info" => str_replace("\xef\xbb\xbf", "", $result)
);
return $return_info;
}
}
?>
|