This repository has been archived by the owner on Oct 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.php
62 lines (50 loc) · 1.46 KB
/
api.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
<?php
/**
* Google URL API Class.
*
* @package Google URL Shortener
* @author Justin Kopepasah
* @version 1.0.0
*/
class Google_URL_API {
// Constructor
function __construct( $key, $api_url = 'https://www.googleapis.com/urlshortener/v1/url' ) {
// Keep the API Url
$this->api_url = $api_url . '?key=' . $key;
}
// Shorten a URL
function shorten( $url ) {
// Send information along
$response = $this->send( $url );
// Return the result
return isset( $response['id'] ) ? $response['id'] : false;
}
// Expand a URL
function expand( $url ) {
// Send information along
$response = $this->send( $url, false );
// Return the result
return isset( $response['longUrl'] ) ? $response['longUrl'] : false;
}
// Send information to Google
function send( $url, $shorten = true ) {
// Create cURL
$ch = curl_init();
// If we're shortening a URL...
if( $shorten ) {
curl_setopt( $ch, CURLOPT_URL, $this->api_url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( array( "longUrl" => $url ) ) );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" ) );
} else {
curl_setopt( $ch, CURLOPT_URL, $this->api_url . '&shortUrl=' . $url );
}
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
// Execute the post
$result = curl_exec( $ch );
// Close the connection
curl_close( $ch );
// Return the result
return json_decode( $result, true );
}
}