
The Stop Online Piracy Act and Protect IP Act impact everyone, learn how these US bills will impact you and your favourite websites internationally.
Now let your voice be heard:
In the last few years URL shortening services have been popping up everywhere. While there are several advantages to using these types of services there are also potential pitfalls:
For more information on possible issues with URL shortening see our article on EndUserThoughts.com: http://www.enduserthoughts.com/archives/16
Depending on your needs you may want or need to setup your own simple URL shortening service, it’s easy and shouldn’t take longer than 30 minutes to create. We’re only going to cover the basics here, depending on your needs you may choose to add more functionality like statistics gathering for example.
For this service you will need a domain with a very short domain-name, preferably this should be something recognizable as connected to your primary domain. Unfortunately for us, eug.ca and eug.com were taken so we’re using our toolset domain, m0m.ca, to run our service. If you don’t already have one, take a look at the available top-level domains out there, there are several two-letter TLD’s available (http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains).
For our service we’ll base the shortened URL tag (or key) on the unique id of the database entry as opposed to the URL itself, this way the tag will always be unique and as short as possible. To keep the tag even shorter, we’ll change the unique id to a different base (base 36) using php’s built-in function base_convert. Note that it’s possible to convert the id with base 62 but this makes the tags case-sensitive which we don’t recommend.
1)The database to store URL’s and keys
2)An .htaccess file with mod-rewrite commands
3)An index.php file
1)new_url.php
2)url_store.php
You need to have a MySQL database setup, in our example the DB Is named ‘url_tool’.
For our service we need to store the following information:
1)ID as required Auto-incrementing integer
2)The full URL as required varchar
3)The shortened url tag as required varchar
4)The title of the document being redirected to as optional varchar
5)The posters IP address as required Integer
The SQL to create this table:
CREATE TABLE `url_tool`.`short` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`url_full` varchar(2083) NOT NULL,
`url_key` varchar(10) NOT NULL,
`title` varchar(100) DEFAULT NULL,
`posterip` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `urlkey` (`url_key`)
) ENGINE=InnoDB AUTO_INCREMENT=0;
We want our URL’s to be as short as possible, that means we need to eliminate URL variables. For example, we want our URL’s to look like this “example.com/1234” instead of “example.com/?id=1234”. To accomplish this, we’re going to use the mod_rewrite module of Apache.
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9A-Za-z]+)/?$ index.php?key=$1 [L]
The index.php file
The index.php file will process any request made to your shortening service and redirect the user to the proper URL, if the page is called without a shortened url tag we’ll redirect to the new URL form
<?php
if (isset($_GET['key']))
{
$DB['host'] = ' '; //Your DB Host
$DB['user'] = ' '; //Your DB Username
$DB['pass'] = ' '; //Your DB Password
$DB['database'] = ' '; //Your DB name
if (!@mysql_connect($DB['host'],$DB['user'],$DB['pass']))
die("<h3>Critical Error: Could not connect to DB</h3>");
if (!@mysql_select_db($DB['database']))
die("<h3>Critical Error: Could not select DB</h3>");
$mykey=mysql_real_escape_string($_GET['key']);
$query="SELECT url_full FROM shrunk WHERE url_key='$mykey'";
$result=mysql_query($query);
if ($result === false)
{
header('Location: error.php');
}
elseif(mysql_num_rows($result)>0)
{
$thekey=mysql_fetch_assoc($result);
$fullurl=$thekey['url_full'];
header('Location: '.$fullurl);
}
else
{
header('Location: error.php');
}
}
else
{
header('Location: new_url.php');
}
?>
The frontend is where you (or other users) enter a URL to be shortened, it consists of a simple form and a separate file to process data entered on the form and insert it into the database we created earlier.
The new_url.php file contains the form where you will enter the URL to be shortened
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Shorten URL</title>
</head>
<body>
<form method="post" action="url_store.php" name="createurl">
<fieldset>
URL to shorten: <input name="url" value="http://" size="80">
<br>
Title (optional):<input size="80">
<br>
<input type="submit">
</fieldset>
</form>
</body>
</html>
The url_store.php file stores the data and displays the shortened URL to the user
<?php
/**
*--url_store.php
*- Receives: URL & Description (title)
*- Processes
*--- Get current pk value
*--- Short URL Key = Convert base of (pk value+1)
*--- Insert DB: short url key, description, user IP address
*- Displays: serviceurl/+shortkey
*/
if(isset($_POST["url"]) && $_POST["url"]!='http://')
{
$DB['host'] = ' '; //Your DB Host
$DB['user'] = ' '; //Your DB Username
$DB['pass'] = ' '; //Your DB Password
$DB['database'] = ' '; //Your DB name
if (!@mysql_connect($DB['host'],$DB['user'],$DB['pass']))
die("<h3>Critical Error: Could not connect to DB</h3>");
if (!@mysql_select_db($DB['database']))
die("<h3>Critical Error: Could not select DB</h3>");
$userIP=getenv("REMOTE_ADDR");
$longurl= mysql_real_escape_string($_POST["url"]);
isset($_POST["urlTitle"])==TRUE ? $title= mysql_real_escape_string($_POST["urlTitle"]) : $TITLE="";
//-- Double-check that the url has not already been shortened, if it has return the original key and exit
//--- Potential improvement: check if the passed title is different, if it is update the DB
$query = "SELECT url_key FROM shrunk WHERE url_full='$longurl'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
if(mysql_num_rows(mysql_query($query)))
$shorten=$row['url_key']; //-- URL has already been shortened
else
{
//-- Get the last used id value from the DB
//--- Note: There are other ways to accomplish this
$query = "SELECT id FROM shrunk ORDER BY id DESC LIMIT 1";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$last_id=$row['id'];
$last_id++; //increment ID by one
$shorten=base_convert($last_id,10,36); //The juice, converts the base from 10 (integer) to 36 (1-9,a-z)
//-- Double-check that key does not already exist, fail with prejudice if it does
$query = "SELECT id FROM shrunk WHERE url_key = '$shorten'";
if(mysql_num_rows(mysql_query($query)))
die ("<h1>FATAL ERROR</h1><p>The shortkey already exists</p>");
//-- Insert the new key into the DB
$insert="INSERT INTO shrunk (url_full,url_key,title,posterip) VALUES('$longurl','$shorten','$title',INET_ATON('$userIP'))";
$result=mysql_query($insert) or die(mysql_error());
}
print "Your short-url is: <a href=\"$shorten\">http://m0m.ca/$shorten</a>";
}
else //If someone tries to access this script without at least the URL post variable set, send them to the form...
header("Location: new_url.php");
?>
That’s all there is to it.