Private URL Shortener With PHP Tutorial

YOURLS is a package that allows you to build your very own link shortening tool, just like the popular bit.ly tool. YOURLS is an open-source package released under the MIT license. This tool can be set up for your own private use which is ideal for things like a social management system or intranet service. Furthermore, you could build an entire link shortener service and compete with the likes of bit.ly!

In this tutorial, we will set up YOURLS on a local PHP stack (XAMPP).

Prerequisites

The Stack

To build this link shortening tool we are going to need the following on the local system/production system.

  • PHP – (Version 7 was used in the tutorial)
  • MySQL
  • Apache

Note: I’m using a XAMPP build.

Custom Local URL

With XAMPP we can define a custom URL using the httpd-vhosts.conf file.

For this tutorial, my custom URL is going to to be http://my.link and the root folder defined as /my – Feel change to change this to suit.

Add the following to the file –

<VirtualHost my.link>
DocumentRoot "C:/xampp/htdocs/my"
ServerName my.link
ServerAlias my.link
<Directory "C:/xampp/htdocs/my">
AllowOverride All
</Directory>
</VirtualHost>

And add the following to your hosts file in C:\Windows\System32\drivers\etc or equivalent.

127.0.0.1 my.link

Create a new DB

Then, it will be a good idea to create a new database in your MySQL build. You can do this with some syntax like below, change the name ‘links_db’ to your desired database name. –

create database my_link_db

 

And that is all the prerequisites we need in place. Now we can move on to setting up and configuring the YOURLS package on our local system.

Download & Install

Step 1

Download the package source files from the releases page on GitHub.

Step 2

Extract the files into a folder in your root directory, the same folder that was referenced in the httpd-vhost.conf file – <Directory "C:/wamp/www/my/"> – Of course, this folder can be the name that suits you, but make sure they match the conf file.

Configuration

Step 1

Locate the config-sample.php file within the /user folder. Make a copy of the config-sample.php file and rename it to config.php.

Step 2

Open the config.php file with your code editor and adjust the following values to suit your environment. For this tutorial, the database created was named my_links_db with the default root username and a blank password.

See below –

/** MySQL database username */
define( 'YOURLS_DB_USER', 'root' );

/** MySQL database password */
define( 'YOURLS_DB_PASS', '' );

/** The name of the database for YOURLS */
define( 'YOURLS_DB_NAME', 'my_links_db' );

/** MySQL hostname.
 ** If using a non standard port, specify it like 'hostname:port', eg. 'localhost:9999' or '127.0.0.1:666' */
define( 'YOURLS_DB_HOST', 'localhost' );

/** MySQL tables prefix */
define( 'YOURLS_DB_PREFIX', 'yourls_' );

/*
 ** Site options
 */

/** YOURLS installation URL -- all lowercase, no trailing slash at the end.
 ** If you define it to "http://sho.rt", don't use "http://www.sho.rt" in your browser (and vice-versa) */
define( 'YOURLS_SITE', 'http://my.link' );

Then, we need to define a username & password, I’ve just used root/password for this tutorial

/** Username(s) and password(s) allowed to access the site. Passwords either in plain text or as encrypted hashes
** YOURLS will auto encrypt plain text passwords in this file
** Read http://yourls.org/userpassword for more information */
$yourls_user_passwords = array(
'username' => 'password',
'root' => 'password',
// You can have one or more 'login'=>'password' lines
);

Step 3

Navigate to the /admin URL in the browser, for this tutorial, it will be http://my.link/admin 

You should be presented with the following page –

yourls install admin page

Step 4

Hit the ‘Install YOURLS’ button, and you should be presented with something like the following screenshot.

yourls install success

Using the URL Shortening tool

Admin Interface

Now, we can navigate to http://my.link/admin/ in the browser and log in with the username and password we defined in the config.php file. Once logged in, we will see the admin interface.

Now we can start utilizing the tool, add your favorite URL to the ‘Enter the URL’ text field, for this example, https://www.codewall.co.uk/ was used. On the right-hand side to this input, add a custom identifier if you want for example ‘cw’. If not, the tool will automatically generate a custom identifier for the short URL.

Lastly, we click shorten the URL, and bam, the link is shortened and added to the database. See the image below –

admin shorten url interface

 

Now, we can literally type in http://my.link/cw in the browser, and the homepage of this blog is loaded. It’s so cool!

 

Another really good feature of this package is when you hover over one of the table rows, some action icons appear. One of which is a ‘stats’ icon, once clicked another page is loaded, see below –

yourls stats page

 

More than one thing worth noting here –

  • The stats page keeps a running total of how many clicks the short URL has had and even graphs this data out. You can see the hits statistics are broken down in 24 hours, last 7 days, last 30 days or all time.
  • It shows the original URL specified for the short link.
  • There is a share tab that allows you to tweet or share on Facebook directly from the interface.
  • Further information tabs on traffic locations and sources.

User Interface

All this is well and good, but, most likely, we want to expose this tool to the front end users. So, how do we do this? Luckily, YOURLS comes ready for this and it’s easy to follow, well-documented API allows you to pass in URLs to be shortened.

Step 1

Let’s build a mini-user front-end.

For simplicity, I’m just going to create an index.html file in the my/ root folder.

Copy the following HTML which includes basic HTML5 markup, calls in Bootstrap & Jquery from a CDN.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My.Link Shortening Tool</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">
        <h1 class="display-4">Shorten Your Link Below</h1>
        <p class="lead">Add your link in the text box below, hit the shorten button and we'll shorten your link!</p>
        <form id="shorten-link-form">
            <div class="input-group mb-3">
                <input type="text" id="custom-url" class="form-control"
                       placeholder="URL To Shorten eg. https://www.codewall.co.uk/"
                       aria-label="URL To Shorten eg. https://www.codewall.co.uk/" aria-describedby="basic-addon2">
                <div class="input-group-append">
                    <button class="btn btn-outline-secondary" type="submit">Shorten</button>
                </div>
            </div>
        </form>
    </div>
</div>


<script src="https://code.jquery.com/jquery-2.2.4.min.js"
        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
        crossorigin="anonymous"></script>

</body>
</html>

This should result in something that looks like the following –

url shortener front end

Next, we want to write the JavaScript that will call to the API, passing in the custom URL the user types in.

Step 2

Add the following JavaScript, just before the closing body tag.

$(document).ready(function () {

        // Listen for Shorten button submit.
        $('#shorten-link-form').submit(function (e) {
            // Test URL is valid
            var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;
            var regEx = new RegExp(expression);
            var customUrl = $('#custom-url').val();
            var isValidUrl = regEx.test(customUrl);

            // If valid, then submit the url to the API.
            if (isValidUrl) {

                e.preventDefault();
                var api_url = 'http://my.link/yourls-api.php';
                var response = $.get(api_url, {
                        username: "root",
                        password: "password",
                        action: "shorturl",
                        format: "json",
                        url: $('#custom-url').val()
                    },
                    function (data) {
                        // If the api returns a short url, then append an alert to the page so the user can copy it.
                        if (data.shorturl !== undefined) {
                            $('.container').append('<div class="alert alert-success alert-dismissible fade show" role="alert">' +
                                '  <strong>Success</strong> Here is your shortened link - . ' + data.shorturl +
                                '  <button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                                '    <span aria-hidden="true">×</span>' +
                                '  </button>\n' +
                                '</div>')
                        }

                    }
                );

            }
        });
    });

A couple of notes about the JS

  • Listen for submit button to be clicked (Shorten button)
  • Prevent the default behavior of submitting to another page.
  • Test the URL isn’t garbage
  • Submit the custom URL to the API & await a response – Make sure you are pointing to the yourls_api.php correctly, in this case, it’s http://my.link/yourls-api.php
  • Once the response is received, append an alert to the page for the user to copy

 

Let’s test it out –

Type in your custom URL to be shortened and hit the Shorten button. Here’s the result below –

shortened url success

And, now if we check the /admin interface, we can see this URL has been registered –

 

shortened url success admin

shortened url success admin 2

 

And that is it!

Summary

This brilliant little tool could be the basis of the next big URL shortening tools! Do you feel like taking on some of the big guys!? Of course, this package is great for a side-of-learning and even to add to some real-life web-systems. YOURLS also has more to offer if you have a dig around of their site too, additional API actions, etc. It’s well worth a look.

One thing about this library is its pure simplistic setup, it really is lovely to use. Let me know in the comments if you get it set up, and even better, if you make a live URL tool with it!

SHARE ON

The Author: Dan Englishby

Private URL Shortener With PHP Tutorial
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.