PHP URL Shortener

PHP URL Shortener

02.Nov.2021

Today I'm going to teach you how to create a fast and efficient URL shortener with PHP. The script, written by myself, is very efficient and can easily handle generating tens of thousands of shortened URLs per hour using only a few server resources. Moreover, it comes with an API that allows you to generate the URLs on the fly just as easily as if they were stored in a database or something similar.

Let's start off by taking a look at the directory structure:

/home/example/public_html/url-shortener |-- configs | `-- defaults.ini |-- includes | |-- api | | `-- index.php (Required for API) | `-- controller | |-- common | | `-- move-to-root.php (Required for API) | |-- error | | `-- index.php | |-- shorten-urls.php | `-- view-statistics.php |-- inc/plugins/ |-- inc/filters.ini |-- public_html

The purpose of each directory is self explanatory, except for the "inc" directories which are where the plugin files go and where filters can be placed respectively. I'll cover those now:

Plugin files should follow this structure to fit into the current naming scheme: <plugin name>.<extension> The file must not contain a php closing tag at the end as this script already contains one that works perfectly fine without it needing to be rerun on every page load or something like that. Filters are used for things such as replacing abbreviations with the full word or capitalizing certain words. You can have an unlimited amount of them in each directory.

Now on to the more interesting parts, the actual code. I'll start with the configs:

<?php // Configuration settings $config['keywords'] = ''; # Put your keywords here separated by commas e.g.: blog, php tutorials $config['api_host'] = 'localhost'; # Your server's IP address or host name $config['shorten_port'] = 8080; # Port number that will be used for both API and Web requests (Optional)

$config['domain'] = 'localhost'; # Replace this with your domain/IP

$config['path_to_directory'] = '/home/example/public_html'; # Replace this with your directory path, leave blank for root  // DO NOT EDIT BELOW THIS LINE! // ------------------------------------------------------ // Now load the defaults config file $configFile = INI_LOAD(DIRECTORY_SEPARATOR . 'defaults.ini'); if ($configFile === FALSE) { return FALSE;}

# These are your default settings in case no configuration values were supplied by the user. You may edit them here. $apiHost = '127.0.0.1'; $shortenPort = 8080; $keywords = ''; # Put your keywords here separated by commas e.g.: blog, php tutorials $domain = 'localhost'; $pathToDirectory = '/home/example/public_html';

// DO NOT EDIT BELOW THIS LINE! // ------------------------------------------------------ # Return TRUE if defaults can be loaded successfully (i.e. no errors) return TRUE; ?>

The keywords setting is used for auto generating unique URLs thus preventing duplication of URLs that use the same set of keywords by trying to convert the supplied keyword list into an MD5 hash. If you don't want it to try and do this, simply leave this blank or delete it from the config file completely. The domain option is used when creating shortened URLs made via the API as it specifies which server to connect to without needing authentication due to the fact that it is on the same server. The shorten port option allows you to specify which port number to use for both API and Web requests, if not supplied defaults are used.

The defaults config file is simply just a list of default settings loaded at start up for your convenience, there's no need to edit these unless you want to change something such as using HTTPS or some other protocol instead of HTTP for example.

The next part of the code deals with changing directory permissions which is basically required in order for this script to work properly. To make things easier I've set it so that all files will be created within your public_html directory through code automatically without having to creating any directories or manually setting file permissions yourself, but you can do that if you wish.

The following code simply recreates the directory specified in the configuration file within public_html or whatever path is actually supplied, this means that for most people it's not really even necessary to edit the script at all, but I'm including it anyway just in case:

<?php # This function creates a new directory in $pathToDirectory with $dirName and returns its full path on success, FALSE on failure. function createNewDirectory($dirName) { $fullPath = $pathToDir . DIRECTORY_SEPARATOR . "\" . $dirName; if (is_writable($fullPath)) { return $fullPath; } else { error_log("Error! Directory {$dirName} could not be created!"); return FALSE; } } # -----------------------------------------------------------?>

That's it for the code, so to summarize all you have to do is put your keywords in the configuration file separated by commas e.g. "blog, php tutorials" and set a domain name if using one, then enter the path to your public_html directory or whatever path you want files that are created by this script to go into. The rest should mostly just work itself out, but no harm checking just in case :)

If you found this useful feel free to leave a comment! Thanks for reading :)

The second part of this article will explain how everything works... stay tuned :) EDIT: Part two of this article is now available here  :) UPDATE: Part two has been expanded to include a comment spam protection system as well as some other improvements! You can find the full source code for this project on my GitHub page here . Thanks :)

PHP URL Shortener with API made using GD library, MySQL and PHP. I have also put together a free e-book explaining how you can create your own social media scripts from scratch using the PHP scripting language. Click here to get a copy of it via email or read more about it here if interested. Please feel free to leave a comment if you found this article useful, thanks :)

We are social