-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshtfy.php
105 lines (89 loc) · 2.38 KB
/
shtfy.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
define("DB_DSN", getenv("SHTFY_DB_DSN"));
define("DB_USER", getenv("SHTFY_DB_USER"));
define("DB_PASSWORD", getenv("SHTFY_DB_PASSWORD"));
define("SITE_URL", getenv("SHTFY_SITE_URL"));
if (isset($_GET["url"]))
{
shorten($_GET["url"]);
die();
}
if (preg_match("|/(\w+)$|", $_SERVER["REQUEST_URI"], $matches))
{
redirect($matches[1]);
die();
}
function get_pdo()
{
static $pdo;
if (!$pdo)
{
$pdo = new PDO(DB_DSN, DB_USER, DB_PASSWORD) or die("database error");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $pdo;
}
function get_token($url)
{
$pdo = get_pdo();
$statement = $pdo->prepare("SELECT id FROM shtfy WHERE url = ?");
$statement->execute(array($url));
$id = $statement->fetchColumn();
if ($id === false)
{
$statement = $pdo->prepare("INSERT INTO shtfy (url) VALUES (?)");
$statement->execute(array($url));
$id = $pdo->lastInsertId();
}
return base62_encode($id);
}
function get_url($token)
{
$pdo = get_pdo();
$id = base62_decode($token);
$statement = $pdo->prepare("UPDATE shtfy SET hits = hits + 1 WHERE id = ?");
$statement->execute(array($id));
$statement = $pdo->prepare("SELECT url FROM shtfy WHERE id = ?");
$statement->execute(array($id));
return $statement->fetchColumn();
}
function shorten($url)
{
if (!preg_match("|^https?://|", $url))
$url = "http://$url";
$token = get_token($url);
print(SITE_URL . $token);
}
function redirect($token)
{
$url = get_url($token);
if (!$url)
$url = SITE_URL;
header("Location: $url", true, 301);
}
// source: http://programanddesign.com/php/base62-encode/
function base62_encode($val)
{
$base=62;
$chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
do {
$m = bcmod($val, $base);
$str = $chars[$m] . $str;
$val = bcdiv(bcsub($val, $m), $base);
} while(bccomp($val,0)>0);
return $str;
}
// source: http://programanddesign.com/php/base62-encode/
function base62_decode($str)
{
$base=62;
$chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$len = strlen($str);
$val = 0;
$arr = array_flip(str_split($chars));
for($i = 0; $i < $len; ++$i) {
$val = bcadd($val, bcmul($arr[$str[$i]], bcpow($base, $len-$i-1)));
}
return $val;
}