Quick Tip: Create a Simple URL Shortener With 10 Lines of PHP

I love to solve problems with tiny, one-off scripts. The fewer lines that I have to write, the better. Recently I had another opportunity to do just that. I needed a way to embed links in PDF documents, the destinations of which I might need to update in the future. Links in PDFs can’t be updated without generating and sending the files again, which is time consuming. The links were also long, and it would be difficult to type them manually if the documents are printed.

This problem can be solved nicely with a URL shortener. Such services have been around for a long time, but there are a few problems with them:

  • You depend on an external service – when it is down, all your links are down. Even worse – if it goes out of business, so do your links.
  • All clicks are being monitored for unknown purposes.
  • You usually can’t change the destination of a short link.
  • Some services allow you to choose a custom slug, but all the good ones have already been taken.

The stage is set for writing a quick and dirty PHP script!

The Idea

If we are to create a link shortening service that you are the only user of, we might omit things like user registrations and admin panels. Here are some of the features of our link shortener:

  • Short links will come in the form http://example.com/l/short-link. Visiting this URL will redirect the browser to the real address.
  • The entire script will be held in a single php file – index.php, without external dependencies.
  • There won’t be an administration screen for adding or editing links. Everything will be handled by a simple text file that sits on your server and which you can edit easily.
  • There won’t be any automatically assigned ids to links – you will choose the short slug yourself.

These requirements greatly simplify the script that we will be writing. To make things even more straightforward, I decided to store the links in an ini file, because it is very easy to edit by hand, and it has native support in PHP via the parse_ini_file function (this will save us from having to read the contents of the file and parsing it ourselves; and as a bonus this function is very fast).

The INI File

Here is what the ini file looks like:

links.ini

google	= https://www.google.com/
fb	= https://www.facebook.com/

Short link on the left, long link on the right. It doesn’t get any simpler than that!

The Code

The PHP script is equally bare bones:

index.php

$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
	header('Location: ' . $links[$_GET['l']]);
}
else{
	header('HTTP/1.0 404 Not Found');
	echo 'Unknown link.';
}

The script expects to receive the slug in $_GET['l'] like so: http://example.com/index.php?l=google. This obviously is not very short, but we can make it prettier with an .htaccess file (assuming you are running the Apache webserver).

.htaccess

RewriteEngine On

RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]

This file should sit in the same folder, next to index.php and links.ini. What it does, is to route every request for a file that is not index.php, to index.php?l=xxx. This prevents infinite loops and also makes links.ini unreachable from a browser.

For the best result, place these three files in a folder with a short name like ‘l’ in the root of your website, and you will get short links like http://example.com/l/google. (Obviously google.com is a poor choice in this case – the short link is longer than the original!)

We’re Done!

If you don’t want to keep a separate file with links, you might eliminate it entirely by placing the short links directly in the script as an associative array. Another improvement might be to build a simple administrative interface that changes the contents of the ini file. I am sure that there even more awesome things that you can do with this code. I hope that you find this tiny script useful!

Join our newsletter and get our PSDs!17,423 people learn about HTML5, JS and more. Join them!

by Martin Angelov

Martin is a web developer with an eye for design from Bulgaria. He founded Tutorialzine in 2009 and publishes new tutorials weekly.

5 Comments

  1. Hiren says:

    Hello Martin,

    I am following your blog on Feedly for longtime. Your all posts are straight forward and easy to understand. I like the idea of changing destination url.

    Thanks

  2. Brad says:

    Great tip, as always.

    I think the URL could be cleaner by using $_SERVER['REQUEST_URI'] instead of $_GET['l'] though.
    A quick example on github

    1. Martin Angelov says:

      Thanks! You've made good improvements to the code. But I think there will be a problem with using $_SERVER['REQUEST_URI'] - it will include the rest of the path, and not only the short slug (e.g. '/l/link' instead of only 'link').

  3. Daniel says:

    Love the simplicity of that.

  4. Sarath says:

    Simply awsome!

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links