forked from neolf/googl-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Googl.class.php
86 lines (73 loc) · 2.31 KB
/
Googl.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/**
* This file is part of googl-php
*
* https://github.com/sebiw/googl-php
*
* googl-php is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Googl
{
public $extended;
private $target;
private $apiKey;
private $ch;
function __construct($apiKey = null) {
# Extended output mode
$extended = false;
# Set Google Shortener API target
$this->target = 'https://www.googleapis.com/urlshortener/v1/url?';
# Set API key if available
if ( $apiKey != null ) {
$this->apiKey = $apiKey;
$this->target .= 'key='.$apiKey.'&';
}
# Initialize cURL
$this->ch = curl_init();
# Set our default target URL
curl_setopt($this->ch, CURLOPT_URL, $this->target);
# We don't want the return data to be directly outputted, so set RETURNTRANSFER to true
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
}
public function shorten($url, $extended = false) {
# Payload
$data = array( 'longUrl' => $url );
$data_string = '{ "longUrl": "'.$url.'" }';
# Set cURL options
curl_setopt($this->ch, CURLOPT_POST, count($data));
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, Array('Content-Type: application/json'));
if ( $extended || $this->extended) {
return json_decode(curl_exec($this->ch));
} else {
return json_decode(curl_exec($this->ch))->id;
}
}
public function expand($url, $extended = false) {
# Set cURL options
curl_setopt($this->ch, CURLOPT_URL, $this->target.'shortUrl='.$url);
if ( $extended || $this->extended ) {
return json_decode(curl_exec($this->ch));
} else {
return json_decode(curl_exec($this->ch))->longUrl;
}
}
function __destruct() {
# Close the curl handle
curl_close($this->ch);
# Nulling the curl handle
$this->ch = null;
}
}
?>