summaryrefslogtreecommitdiff
path: root/linkshorter/insert.php
blob: 94d01a390b36bd7de0a20f7742d1b33b4592199e (plain)
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
<?php

if ( $_SERVER['REQUEST_METHOD'] != 'POST'){
	header($_SERVER['SERVER_PROTOCOL'] . " 301 Moved Permanently");
	header("Location: http://". $_SERVER["HTTP_HOST"] . "/");
	exit;
}

require 'functions.php';

if ( empty($_POST["url"]) || $_POST["url"] == "" ){
	failure("<p>We need a link to be shortened.</p>", false, "400 Client Failed", "<h1>Missing URL</h1>");
} 

if ( ! preg_match("/^[a-z]+:\/\/[a-z0-9_]+/i", $_POST["url"]) ){
	failure("<p>Only schemas like http:// or ftp:// are supported.</p>", false, "400 Client Failed", "<h1>This does not look like an url</h1>");
}

require 'db.php';

$hash = md5($_POST["url"]);
if( ! $short = $db->get($hash)){

	$arr = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");

	$short="";
	for ($i=0;$i<5;$i++){
        	$r = mt_rand(0, count($arr)-1);
	        $short.=$arr[$r];
	}

	$db->set($short, $_POST["url"]);
	$db->set($hash, $short);;
}

failure("<p>Your short link for <a href=\"".htmlentities($_POST["url"])."\">".htmlentities($_POST["url"])."</a> is <br> <a href=\"http://".$_SERVER["HTTP_HOST"] . "/-" . $short ."\">http://".$_SERVER["HTTP_HOST"]."/-".$short."</a></p>", false, "200 OK", "<h1>Success</h1>");