Skip to content

Commit

Permalink
Initial project files
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Cray committed Nov 23, 2010
0 parents commit 6a70a9c
Show file tree
Hide file tree
Showing 8 changed files with 268 additions and 0 deletions.
36 changes: 36 additions & 0 deletions README
@@ -0,0 +1,36 @@
License: http://creativecommons.org/licenses/by/3.0/

Benefits

- Can shorten over 42 billion unique URLs in 6 or less characters (it can do more than 12,000,000 in only 4!)
- Super duper fast—uses very little server resources
- Includes an API so you can create your own short URLs on the fly
- Option to turn clickthru tracking on and off
- Option to limit usage to 1 IP address for personal use and to prevent spamming from others
- Only uses alphanumeric characters so all browsers can interpret the URL
- Secure—several data filters in place to prevent SQL injection hacks
- Option to check if the URL is real (doesn’t respond with a 404) before shortening
- Uses 301 redirects for SEO and analytics yumminess
- Option to store a local cache to prevent database queries on every redirect
- Option to change the characters allowed in a shortened url

Installation

1. Make sure your server meets the requirements:
a) Optionally you can run this from your current domain or find a short domain
b) Apache
c) PHP
d) MySQL
e) Access to run SQL queries for installation
2. Download a .zip file of the PHP URL shortener script files
3. Upload the contents of the .zip file to your web server
4. Update the database info in config.php
5. Run the SQL included in shortenedurls.sql. Many people use phpMyAdmin for this, if you can’t do it yourself contact your host.
6. Rename rename.htaccess to .htaccess
7. If you want to use the caching option, create a directory named cache with permissions 777

Using your personal URL shortener service

- To manually shorten URLs open in your web browser the location where you uploaded the files.
- To programmatically shorten URLs with PHP use the following code:
$shortenedurl = file_get_contents('http://yourdomain.com/shorten.php?longurl=' . urlencode('http://' . $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI']));
38 changes: 38 additions & 0 deletions config.php
@@ -0,0 +1,38 @@

/*
* First authored by Brian Cray
* License: http://creativecommons.org/licenses/by/3.0/
* Contact the author at http://briancray.com/
*/

// db options
define('DB_NAME', 'your db name');
define('DB_USER', 'your db usernae');
define('DB_PASSWORD', 'your db password');
define('DB_HOST', 'localhost');
define('DB_TABLE', 'shortenedurls');

// connect to database
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);

// base location of script (include trailing slash)
define('BASE_HREF', 'http://' . $_SERVER['HTTP_HOST'] . '/');

// change to limit short url creation to a single IP
define('LIMIT_TO_IP', $_SERVER['REMOTE_ADDR']);

// change to TRUE to start tracking referrals
define('TRACK', FALSE);

// 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/');
21 changes: 21 additions & 0 deletions index.html
@@ -0,0 +1,21 @@
<p>If you are seeing this, your <code>.htaccess</code> file is configured incorrectly or doesn't exist.</p>
<p>Copy and paste the code below into your <code>.htaccess</code> file</p>
<pre>
DirectoryIndex index.php

php_flag register_globals off
php_flag magic_quotes_gpc off

FileETag none
ServerSignature Off

Options All -Indexes

&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteRule ^shorten/(.*)$ shorten.php?longurl=$1 [L]
RewriteRule ^([0-9a-zA-Z]{1,6})$ redirect.php?url=$1 [L]
&lt;/IfModule&gt;
</pre>

<p>For detailed instructions, visit Brian Cray</p>
23 changes: 23 additions & 0 deletions index.php
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<title>URL shortener</title>
<meta name="robots" content="noindex, nofollow">
</html>
<body>
<form method="post" action="shorten.php" id="shortener">
<label for="longurl">URL to shorten</label> <input type="text" name="longurl" id="longurl"> <input type="submit" value="Shorten">
</form>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#shortener').submit(function () {
$.ajax({data: {longurl: $('#longurl').val()}, url: 'shorten.php', complete: function (XMLHttpRequest, textStatus) {
$('#longurl').val(XMLHttpRequest.responseText);
}});
return false;
});
});
</script>
</body>
</html>
56 changes: 56 additions & 0 deletions redirect.php
@@ -0,0 +1,56 @@
<?php
/*
* First authored by Brian Cray
* License: http://creativecommons.org/licenses/by/3.0/
* Contact the author at http://briancray.com/
*/

ini_set('display_errors', 0);

if(!preg_match('|^[0-9a-zA-Z]{1,6}$|', $_GET['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(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);
@mkdir(CACHE_DIR, 0777);
$handle = fopen(CACHE_DIR . $shortened_id, 'w+');
fwrite($handle, $long_url);
fclose($handle);
}
}
else
{
$long_url = mysql_result(mysql_query('SELECT long_url FROM ' . DB_TABLE . ' WHERE id="' . mysql_real_escape_string($shortened_id) . '"'), 0, 0);
}

if(TRACK)
{
mysql_query('UPDATE ' . DB_TABLE . ' SET referrals=referrals+1 WHERE id="' . mysql_real_escape_string($shortened_id) . '"');
}

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);
}
return $out;
}
17 changes: 17 additions & 0 deletions rename.htaccess
@@ -0,0 +1,17 @@
DirectoryIndex index.php

# remove the next 3 lines if you see a 500 server error
php_flag register_globals off
php_flag magic_quotes_gpc off
php_value display_errors 0

FileETag none
ServerSignature Off

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>
63 changes: 63 additions & 0 deletions shorten.php
@@ -0,0 +1,63 @@
<?php
/*
* First authored by Brian Cray
* License: http://creativecommons.org/licenses/by/3.0/
* Contact the author at http://briancray.com/
*/

ini_set('display_errors', 0);

$url_to_shorten = get_magic_quotes_gpc() ? stripslashes(trim($_REQUEST['longurl'])) : trim($_REQUEST['longurl']);

if(!empty($url_to_shorten) && preg_match('|^https?://|', $url_to_shorten))
{
require('config.php');

// check if the client IP is allowed to shorten
if($_SERVER['REMOTE_ADDR'] != LIMIT_TO_IP)
{
die('You are not allowed to shorten URLs with this service.');
}

// check if the URL is valid
if(CHECK_URL)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_to_shorten);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($handle);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '404')
{
die('Not a valid URL');
}
}

// 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))
{
// URL has already been shortened
$shortened_url = getShortenedURLFromID($already_shortened);
}
else
{
// URL not in database, insert
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']) . '")');
$shortened_url = getShortenedURLFromID(mysql_insert_id());
mysql_query('UNLOCK TABLES');
}
echo BASE_HREF . $shortened_url;
}

function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
$length = strlen($base);
while($integer > $length - 1)
{
$out = $base[fmod($integer, $length)] . $out;
$integer = floor( $integer / $length );
}
return $base[$integer] . $out;
}
14 changes: 14 additions & 0 deletions shortenedurls.sql
@@ -0,0 +1,14 @@
--
-- Table structure for table `shortenedurls`
--

CREATE TABLE `shortenedurls` (
`id` int(10) unsigned NOT NULL auto_increment,
`long_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`),
KEY `referrals` (`referrals`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

0 comments on commit 6a70a9c

Please sign in to comment.