-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
49 lines (35 loc) · 1.24 KB
/
index.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
<?php
require 'libraries/klein.php';
require 'libraries/Mongo_db.php';
include 'config/config.php';
respond(function ($request, $response, $app) {
global $config;
$app->db = new Mongo_db($config['mongo']);
});
respond('/', function ($request, $response) {
$response->render('html/home.html');
});
respond('/shorten', function($request, $response, $app) {
global $config;
$url = $_POST['url'];
if(!$_POST['url']) exit(json_encode(array('status' => 'error', 'message' => 'No URL inserted!')));
if(!filter_var($url, FILTER_VALIDATE_URL)) exit(json_encode(array('status' => 'error', 'message' => 'This is not a url!')));
$short = getShort();
$app->db->insert('urls', array('url' => $url, 'short' => $short));
echo json_encode(array('status' => 'success', 'short' => $config['site']['base_url'].'s/'.$short));
});
respond('/s/[:shorturl]', function ($request, $response, $app) {
$shorturl = $request->param('shorturl');
$url = $app->db->where(array('short' => $shorturl))->get('urls');
$url = $url[0];
$response->redirect($url['url']);
});
function getShort() {
$uniqid = uniqid();
$length = strlen($uniqid);
$characters = 5;
$start = $length - $characters;
$uniqid = substr($uniqid , $start ,$characters);
return $uniqid;
}
dispatch();