Permalink
Browse files

Massive code cleanup, with more error checking everywhere. Now genera…

…tes randomised length URLs instead of just incrementing.
  • Loading branch information...
lozzd committed May 18, 2011
1 parent 045c715 commit c5e3a3c07196b5f51a41770744cf85995382688e
Showing with 50 additions and 42 deletions.
  1. +5 −5 config.php
  2. +25 −21 redirect.php
  3. +2 −2 rename.htaccess
  4. +15 −13 shorten.php
  5. +3 −1 shortenedurls.sql
View
@@ -1,4 +1,4 @@
-<?PHP
+<?php
/*
* First authored by Brian Cray
* License: http://creativecommons.org/licenses/by/3.0/
@@ -19,6 +19,9 @@
// base location of script (include trailing slash)
define('BASE_HREF', 'http://' . $_SERVER['HTTP_HOST'] . '/');
+// how long do you want your URLs?
+define('SHORT_LENGTH', 5);
+
// change to limit short url creation to a single IP
define('LIMIT_TO_IP', $_SERVER['REMOTE_ADDR']);
@@ -28,12 +31,9 @@
// check if URL exists first
define('CHECK_URL', FALSE);
-// change the shortened URL allowed characters
-define('ALLOWED_CHARS', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
-
// do you want to cache?
define('CACHE', TRUE);
// if so, where will the cache files be stored? (include trailing slash)
define('CACHE_DIR', dirname(__FILE__) . '/cache/');
-?>
+?>
View
@@ -7,51 +7,55 @@
ini_set('display_errors', 0);
-if(!preg_match('|^[0-9a-zA-Z]{1,6}$|', $_GET['url']))
+$url = $_GET['url'];
+
+if(!preg_match('|^[0-9a-zA-Z]{1,10}$|', $url))
{
die('That is not a valid short url');
}
require('config.php');
-$shortened_id = getIDFromShortenedURL($_GET['url']);
-
if(CACHE)
{
- $long_url = file_get_contents(CACHE_DIR . $shortened_id);
+ if(file_exists(CACHE_DIR . $url)) {
+ $long_url = file_get_contents(CACHE_DIR . $url);
+ }
if(empty($long_url) || !preg_match('|^https?://|', $long_url))
{
- $long_url = mysql_result(mysql_query('SELECT long_url FROM ' . DB_TABLE . ' WHERE id="' . mysql_real_escape_string($shortened_id) . '"'), 0, 0);
+ $long_url = getLongURL($url);
@mkdir(CACHE_DIR, 0777);
- $handle = fopen(CACHE_DIR . $shortened_id, 'w+');
- fwrite($handle, $long_url);
- fclose($handle);
+ if (is_writeable(CACHE_DIR) && $handle = fopen(CACHE_DIR . $url, 'w+')) {
+ fwrite($handle, $long_url);
+ fclose($handle);
+ } else {
+ trigger_error("Your cache directory, " . CACHE_DIR . " does not exist or is not writeable. continuing anyway, but consider setting CACHE to false.", E_USER_WARNING);
+ }
}
}
else
{
- $long_url = mysql_result(mysql_query('SELECT long_url FROM ' . DB_TABLE . ' WHERE id="' . mysql_real_escape_string($shortened_id) . '"'), 0, 0);
+ $long_url = getLongURL($url);
}
if(TRACK)
{
- mysql_query('UPDATE ' . DB_TABLE . ' SET referrals=referrals+1 WHERE id="' . mysql_real_escape_string($shortened_id) . '"');
+ mysql_query('UPDATE ' . DB_TABLE . ' SET referrals=referrals+1 WHERE short_url="' . mysql_real_escape_string($url) . '"');
}
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $long_url);
exit;
-function getIDFromShortenedURL ($string, $base = ALLOWED_CHARS)
-{
- $length = strlen($base);
- $size = strlen($string) - 1;
- $string = str_split($string);
- $out = strpos($base, array_pop($string));
- foreach($string as $i => $char)
- {
- $out += strpos($base, $char) * pow($length, $size - $i);
+function getLongURL($shorturl) {
+ $results = mysql_query('SELECT long_url FROM ' . DB_TABLE . ' WHERE short_url="' . mysql_real_escape_string($shorturl) . '"');
+ if ((!$results) || (mysql_num_rows($results) == 0)) {
+ header('HTTP/1.1 404 Not Found');
+ die("404 - This short URL does not exist. ");
+ } else {
+ $long_url = mysql_result($results, 0, 0);
+ return $long_url;
}
- return $out;
}
-?>
+
+?>
View
@@ -13,5 +13,5 @@ Options All -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^shorten/(.*)$ shorten.php?longurl=$1 [L]
-RewriteRule ^([0-9a-zA-Z]{1,6})$ redirect.php?url=$1 [L]
-</IfModule>
+RewriteRule ^([0-9a-zA-Z]{1,10})$ redirect.php?url=$1 [L]
+</IfModule>
View
@@ -35,31 +35,33 @@
}
// check if the URL has already been shortened
- $already_shortened = mysql_result(mysql_query('SELECT id FROM ' . DB_TABLE. ' WHERE long_url="' . mysql_real_escape_string($url_to_shorten) . '"'), 0, 0);
- if(!empty($already_shortened))
- {
+ $results = mysql_query('SELECT id FROM ' . DB_TABLE. ' WHERE long_url="' . mysql_real_escape_string($url_to_shorten) . '"');
+ if (mysql_num_rows($results) != 0) {
// URL has already been shortened
+ $already_shortened = mysql_result($results, 0, 0);
$shortened_url = getShortenedURLFromID($already_shortened);
}
else
{
// URL not in database, insert
+ // Generate a short URL
+ $short_url = substr(base_convert(md5($url_to_shorten),16, 36),0,SHORT_LENGTH);
+ $long_url = mysql_real_escape_string($url_to_shorten);
+ $remote_addr = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query('LOCK TABLES ' . DB_TABLE . ' WRITE;');
- mysql_query('INSERT INTO ' . DB_TABLE . ' (long_url, created, creator) VALUES ("' . mysql_real_escape_string($url_to_shorten) . '", "' . time() . '", "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '")');
+ $result = mysql_query('INSERT INTO ' . DB_TABLE . ' (long_url, short_url, created, creator) VALUES ("' . $long_url . '", "' . $short_url . '", "' . time() . '", "' . $remote_addr . '")');
+ if (!$result) {
+ die("Insert into DB failed");
+ }
$shortened_url = getShortenedURLFromID(mysql_insert_id());
mysql_query('UNLOCK TABLES');
}
echo BASE_HREF . $shortened_url;
}
-function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
+function getShortenedURLFromID ($integer)
{
- $length = strlen($base);
- while($integer > $length - 1)
- {
- $out = $base[fmod($integer, $length)] . $out;
- $integer = floor( $integer / $length );
- }
- return $base[$integer] . $out;
+ $shorturl = mysql_result(mysql_query('SELECT short_url FROM ' . DB_TABLE. ' WHERE id=' . mysql_real_escape_string($integer) ),0,0);
+ return $shorturl;
}
-?>
+?>
View
@@ -5,10 +5,12 @@
CREATE TABLE `shortenedurls` (
`id` int(10) unsigned NOT NULL auto_increment,
`long_url` varchar(255) NOT NULL,
+ `short_url` varchar(255) NOT NULL,
`created` int(10) unsigned NOT NULL,
`creator` char(15) NOT NULL,
`referrals` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`id`),
UNIQUE KEY `long` (`long_url`),
+ UNIQUE KEY `short` (`short_url`),
KEY `referrals` (`referrals`)
-) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;

0 comments on commit c5e3a3c

Please sign in to comment.