URL shortening is widely used and there are a number of sites, such as tinyurl, that offer the service for free. So, why roll your own?
- Because it’s easy. Using PHP, MySQL, and Apache , it can be done in 3 steps that can take only 15 minutes.
- You reduce your dependency on external services. If a site like tinyurl was to go out of business, any links published through them would be dead.
- You can use any short names you want .
Step 1: Create the schema in MySQL
Login to MySQL and run these queries:
CREATE DATABASE my_tinyurl ;
USE my_tinyurl; -- Create a table to hold the mapping from short URL to real URL CREATE TABLE links ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, link VARCHAR(255), short_link VARCHAR(100) ); -- Add a user and grant privileges for the database: : CREATE USER ‘tinyurl_user'@'localhost' IDENTIFIED BY 'password'; GRANT SELECT,INSERT,UPDATE,DELETE ON my_tinyurl.* TO ‘tinyurl_user'@'localhost';
-- Add one record for testing INSERT INTO links (link,slink) VALUES ('http://bootstrapsoftware.com','b');
Step 2: Script the translation service
Create a file called index.php and place this code inside
<?php # connect to the database $db = mysql_connect('127.0.0.1','tinyurl_user','password') or die("Database error"); mysql_select_db('my_tinyurl', $db); # get the real link $domain_name = mysql_escape_string($_GET[domain]); $result = mysql_query("SELECT link FROM links where short_link = ‘$domain_name’"); $array = mysql_fetch_assoc($result); $redirect = (is_null($array['link'])) ? "http://google.com" : = $array['link']; header(“Location: $redirect”); ?>
Step 3: Rewrite the short link as a GET parameter
In the same directory as index.php, create a .htaccess file and place the following rewrite rules inside:
RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) /link/index.php?domain=$1 [L]
New links can be added by manually inserting them into the database. Or, an html GUI and PHP script can be created to add them.
How might you use a service such as this as part of your application or business?