Creating a Simple Short URL Service Without Any Database

I wanted to create a really simple short url service for the permalinks on this website ( by using the domain

Here is what I came up with:

  // Go to a URL like 
  // To generate a URL like
  $data = file_get_contents('data.json');
  $json = json_decode($data, true);
  $short_url = substr($_SERVER['REQUEST_URI'], 1);

  if ($json[$short_url]) {
    // Cache the redirect in the browser
    header('HTTP/1.0 301 Moved Permanently');
    header("Location: $json[$short_url]");
    header('Cache-Control: private');
    header('Vary: User-Agent, Accept-Encoding');
  } else if ($_GET['q'] === '/short' && $_GET['url']) {
    // Generate the unqiue string for the short url
    function generate_key() {
      $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      $random_key = '';

      // For this, I am using 4 characters as the length of my short URLs
      for ($i = 0; $i < 4; $i++) {
        // 61 = length of $chars - 1
        $random_key .= $chars[rand(0, 61)];

      return $random_key;

    if (!in_array($_GET['url'], array_values($json))) {
      $url_key = generate_key();

      while (in_array($random, array_keys($json))) {
        $url_key = generate_key();

      $json[$url_key] = $_GET['url'];
      file_put_contents('data.json', json_encode($json, true));
    } else {
      $url_key = array_search($_GET['url'], $json);

    echo "<input onClick=';' readonly='true' value='$url_key' />";
  } else {
    echo 'Read:';

The above PHP code uses a JSON file which would be located in the same folder as this PHP file. This also means that the JSON file needs to be initialized (echo '{}' >> 'data.json') and with the right permissions (chmod 666 data.json <- give every user read + write access).

n.b. Since it doesn’t use a database, but rather reads (and writes) to the JSON file for every operation, this isn’t exactly built to scale.

Additionally, this is the Nginx configuration file I use for routing at (the error_page, fastcgi, etc, sections are irrelevant, but I’d rather share the entire file).

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /var/www/shorturl/html/;
  index index.php index.html index.htm;


  location / {
    try_files $uri $uri/ /index.php?q=$uri&$args;

  error_page 404 /404.html;
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
    root /usr/share/nginx/html;

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;

Source also located at (for ZIP download, etc).

1 Weird Trick to Decrease Your Website’s Load Time

<link rel="icon" href="data:;base64,iVBORw0KGgo=">

If your website/web app doesn’t use a favicon, then add the above code in your <head>. This is because even if you don’t use a favicon, the browsers usually make a network call to get a favicon.ico in the root directory, and preventing that network call can save your website around 20 ms.

Sticky CSS Footer

Here’s how you should (or can) do a sticky CSS Footer.

Assuming the HTML looks something like this (and everything non footer is inside the “content” div)

<!DOCTYPE html>
  <title>Sticky Footer</title>
  <div class="content">&nbsp;</div>
  <footer>&copy; 2016</footer>

The easiest way to make the footer stick to the bottom would be to use some CSS like

body {
    margin: 0; /* If not already reset */

.content {
    min-height: calc(100vh - 20px);

footer {
    height: 20px;

This makes the “content” div take the minimum vertical height of the entire screen, minus 20 pixels (the fixed height of the footer).

Most of the search results when Googling “sticky CSS footer” are half a decade old, but this is how a sticky CSS footer should be easily implemented in 2016.

Simple React Typeahead & Faster Array Filter

Here is a super simple yet nicely working React typeahead I created couple of days ago after pretty much not being able to find any bug free & lightweight typeahead for React.

It’s weird because while there are too many Typeahead[s] for AngularJS, while I guess React is still in the awkward teenage phase.

Also, I ended up creating a custom Array filter, because well, it is evidently much faster than the native Array.prototype.filter().

The faster Array filter can be defined as:

Array.prototype.where = Array.prototype.where || function(t) {
  var results = [];

  for(var i = 0, len = this.length; i < len; i++) {
    var item = this[i];

    if (t(item)) {

  return results;

Although I don’t think there is going to be any noticeable difference unless the size of array is quite large.

Function Maps in JavaScript

var map = {
  functionOne: function(obj) {
    return'I am at functionOne: %o', obj);
  functionTwo: function(obj) {
    return'I am at functionTwo: %o', obj);
  functionThree: function(obj) {
    return'I am at functionThree: %o', obj);

C like function map which can then be used like map.functionOne({foo: 'bar'}).

I prefer to use objects like these instead of more typical control flow statements like if/else or switch. The map object can be called like map[key]({hello: 'World'}) , where key is the string.

Suppose you’re getting a data array of objects from some request, I can very neatly check all the items using something like this:

var arr ={
    return item[map[key](item)];

Copy JavaScript Array with All Items Except One

var newArr = (newArr = oldArr.slice(), newArr.splice(newArr.indexOf(item), 1), newArr);

By combining JavaScript’s comma operator, Array slice and Array splice, we can conditionally duplicate JavaScript arrays.

Example code:

// Removing '3' from the new Array.
var a = [1, 2, 3, 4, 5];
var b = (b = a.slice(), b.splice(2,1), b);
// b = [1, 2, 4, 5];

Here we have to use a.slice() to copy Array a to b. Otherwise changes made to b would reflect on a as well.

Further Reading

Best Programming Language for Web Development

Disclaimer: I’m not really going to mention any language as ‘best’. The title of this post is actually very misleading.

I started doing hard core web development barely a year ago, but a question I face on a daily basis is whether I’m using an optimal programming language and technology. When I started making websites (not web apps) around four years ago, I used to create them using simple HTML + CSS. Then as my clients needed things which were ‘dynamic’ and wanted to jump on the then popular boat of ‘CMS’, I switched to WordPress for delivering websites. WordPress became my one stop solution for all sorts of websites (although it is actually a blog software with lots of code/functionality which you will probably never need). Soon I started developing on WordPress (plugins) for further delivering to custom requirements. I almost always ended up using a dozen WordPress API methods throughout my code and usually had no any idea how they did what they did.

When I moved to the corporate scene of web development (in my current job), I started using PHP for building web applications. I started using (and still use) frameworks like CodeIgniter (for old projects) and Laravel (newer and cooler). PHP is the most dominantly used server side language right now, powering at least two third of the Internet (source). It is also the web language which gets the maximum hate. The Internet is filled with articles criticizing PHP and then articles trying to justify its usage.

Last semester I started going to hackathons, and pretty much everyone in every hackathon I went, told me how much PHP sucked when I used to tell them that I code in PHP. The common thing about those people was most of them had never actually even used PHP, but were fancied by other ‘cool’ languages. When everyone everywhere I met went totally berserk for PHP, while enchanting how cool Python is (which it actually is btw), I finally made my move to Python (Flask) for web development. It was very cool in syntax and all that (no ugly braces anymore, no more couple of $ signs in every single line), but I did feel that I wasn’t doing anything significantly different than what I could have done using Laravel + Composer/Packagist.

In my opinion, the biggest problem of PHP is the very low bar of entry. Most of the other languages require at least some sort of initial setting up/program compilation for producing even the Hello World but in PHP it’s as easy as writing <?= 'Hello World' ?> in any text file saved with a .php extension. Even almost all of the shared web servers online come with PHP only preinstalled. Because of this PHP becomes the choice of programming for every Joe pretending to be a web developer. What this usually results in is ugly PHP code mixed with HTML, plus five redundant functions doing the same thing and unsanitized SQL queries– all in the same page. This is the stuff which makes PHP bad; but the developers are responsible, not the language.

I’m not saying PHP is the best and greatest programming language. There are certainly more promising languages, like Python, Erlang and Haskell. I just believe PHP is not as bad as everyone claims it to be. There must be a reason why Facebook, Yahoo, Etsy and Mailchimp still use it (although Facebook doesn’t use the php which we use). If people try to follow good coding practices in PHP, it will certainly come out to be as good as other languages (if not greater).

All this being said and as I mentioned above, there are some languages which certainly seem to be very promising for web development. I actually love Python too a lot for writing server side code. Also Erlang too is pretty cool and defines efficiency. Whatsapp, the mobile phone app which was sold couple of days/weeks ago to Facebook had around half a billion users while having just thirty two employees and twenty support people. It is believed that the team was able to pull something like that off because of their strong software in place, which was made using Erlang. Then there is Haskell, which is known for delivering crazy fast websites. I guess if someone wants to know ‘Best Web Programming Language’ for him or herself, the only way to know it is by using each of them. As the quote goes “Never judge a book by its cover”, so is applicable to programming languages.

Further Reading

Ways to Build a Website

There are bunch of ways by which we can get a website up on the Internet. Each way has it’s merits and demerits. In this post I’ll share some ways which I think are fairly quick if you need a simple website up in minimal time. These ways are listed in the order of their coolness.

Static Website Template

If you don’t need anything fancy, then this is certainly the way to go. Just get a nice and pretty looking template from one of those template websites like Themeforest.


  1. Usually these templates are quite pretty.
  2. Several categories to chose from for templates (like restaurants, medical, etc).
  3. Come with stock/dummy content + images, which are easy to replace.
  4. Support is decent if you buy from a legitimate place.
  5. At times there are free templates too!


  1. You need to somewhat know your way around HTML/CSS. Otherwise the result won’t be very nice.
  2. Very generic templat-ey looking websites.
  3. Usually overloaded with a dozen varieties of galleries, sliders, etc, thus not efficient.
  4. Can be difficult to maintain if the number of pages in your website is not in single digits.

WordPress Website

I personally used to use WordPress for creating normal and just about every kind of website, and did so for couple of years until I realized how horrible that idea was. However, I believe this is still the most popular way to get static and dynamic websites up. I’m not saying the idea of using WordPress for normal websites is bad, just that I personally don’t like use things which are an overkill. WordPress is loaded and powerful, but do evaluate if you need all those features or not, and if using it is worth it. I use WordPress for this website because this place is essentially a blog only (and WordPress provides me with all the functionality I need).


  1. Everything from above, plus:
  2. You get a backend enabled website (CMS) fairly easily.
  3. Thus you can easily add or remove pages and maintain them too.
  4. Lots of plugins for quick functionality.
  5. Comes with blog! (duh)
  6. Most ideal for typical users.


  1. Everything from above (except 4), plus:
  2. The templates are not exactly flexible, it’s alright if you need to change the styling, but if you need to do structural stuff, you are better of creating your own template using something like
  3. I don’t like the file structure and code modularity of WordPress websites.
  4. Not very scalable (at least not neatly), although you can create bunch of plugins for doing bunch of stuff, but there is no central approach like present in other web frameworks.
  5. Most people usually tend to use several plugins and most many of these plugins will slow your website down.

Python/PHP Frameworks

If you kind of know your way around web development, then this is what you should probably do. There are bunch of awesome frameworks but top two (according to me) for a fairly functional website would Flask and Laravel (Python and PHP Web Frameworks). They both offer some great features like front end templates (Jinja2 and Blade) and are driven by things like template inheritance, etc. I know this may not be the most efficient solution for just a website, but it all depends upon your velocity. Personally I can more quickly and more neatly set up a website using Laravel than WordPress.


  1. Nice, clean and structured code base (because you authored most of it yourself).
  2. These frameworks typically have many modules/extensions which you use for a plethora of tasks (like ORMs for querying databases, form classes for HTML forms, etc).
  3. You write less code because of these already available modules/classes, and typically the building blocks behind these are pretty good.
  4. Because of these, your web site/application would typically be very easy to scale and maintain.


  1. You actually jumped to web development from web designing here.
  2. You need to be somewhat familiar with web development using Python or PHP.
  3. Maybe be an overkill for many people.

Website Builders

This is typically what people who have no idea about how to make websites do. They are usually offered from shared web hosting providers (like 1&1 Website Builder, etc) and are targeted towards users with no web design experience. There are also services which only do this, two most popular ones of this kind are Squarespace and Virb (owned by Media Temple (which is owned by GoDaddy)).


  1. Best option for people with no design experience.
  2. You can still end up with a decent looking website since they have a wide range of existing templates to chose from.
  3. Quite fast. It’s like using a rich text editor- for websites.


  1. Scalability and Flexibility? Lol.
  2. Not so much for customizations either.
  3. No matter what they advertise, but most of the websites which come out of tools like these don’t look very good.

Honorary Mentions

There are also tools like Concrete5 and Sitefinity CMS, in which case I think you would probably be better of with WordPress and also things like Expressions Engine and KendoUI, which I don’t really know what is and how they are better than their free counterparts.

A Guide to Future Proof Mobile/Tablet Friendly Websites

Tablet and Phones
In a matter of couple of years, more than half of total web browsing will be done from mobile devices, however, mobile devices don’t necessarily provide the same design implementation as desktop computers do and many of times we see our websites breaking on those small screens, while many designers create tablet/mobile specific website, but I think maintaining one website is better than maintaining two separate ones. Below I will discuss some importanr things which we can keep in mind while creating a website to make it future proof for mobile devices as well as desktop computers.

Use Responsive Frameworks

Responsive Web Design
Getting back to the idea of two separate websites, I don’t think it pleases me or anyone much, we are better off doing one Responsive Website. Well, what is this Responsive Website exactly? Wikipedia defines Responsive Web Design as

Responsive Web Design (RWD) essentially indicates that a web site is crafted to use Cascading Style Sheets 3 media queries, an extension of the @media rule, with fluid proportion-based grids, to adapt the layout to the viewing environment, and probably also flexible images. Which means, having a responsive website enables us serve all devices via a single website, it enables us to address the ever-changing screen sizes, orientations and resolutions by using a flexible/fluid grid which will adapt to any screen size (and resolution). With responsive design, we have one website which serves all kinds of devices. This is in contrast from the other trend where we need to maintain at least two websites (desktop and mobile version). It has an obvious major advantage of far easier maintenance (now we maintain one instead of two websites). The essential concept of responsive design is minimum (or no) of resizing, scrolling (horizontal) and panning. There are many frameworks for fluid grids out there, I like the the 1140px CSS Grid and those who are loyal to 960px width can check out Gumby 960 CSS Framework.

Use Media Queries, everywhere

Media queries are certainly the most important part of responsive websites. Media queries were restricted in CSS2 to only screen, print and all, but, in CSS3 they are far more robust. We can now apply different stylesheets/styles based on the size of the viewport and pixel densities. Generally, for the most part, website implementation looks similar in tablets and desktops, however, many elements tend to get implemented (or displayed) differently in tablets, we can fix those elements using specific CSS thanks to media queries, also, we can differentiate how a particular element or the whole website will look in small screen phones, smart phones, tablets and desktops using media queries only. Here I am sharing some essential media queries.

Media Query for Normal Phones

We can include all of our phone specific styles within this block:

@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
    /* ==================================== */
    /* ! All phone specific CSS goes here */
    /* ==================================== */

Media Query for Smart Phones

The difference between a smartphone and a normal phone is resolution, smart phones will always higher resolution than normal phones, we can include all of our smart phone specific styles within this block:

@media handheld,
only screen and (max-width: 767px) {
    /* ========================================= */
    /* ! All smartphone specific CSS goes here */
    /* ========================================= */

Media Query for Tablets

We can use the below media query for all of our tablet specific styles, do keep in mind this will not get applied to those 10 inches tablets like Motorola Xoom, Toshiba Thrive, etc and will get applied to small/old monitors.

@media only screen and (min-device-width: 600px) and (max-device-width: 1024px) {
    /* ===================================== */
    /* ! All tablet specific CSS goes here */
    /* ===================================== */

Media Query for New Retina Displays

If we have some high resolutions assets which we will like to be applied to iPhone 4, iPhone 4S and iPad 3, then we can use the below block:

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
    /* =================================== */
    /* ! Higher resolution CSS goes here */
    /* =================================== */

Taking Care of Orientation Problems As I discussed in my post:

Making Devices on Portrait Orientation Behave like Mobile, some websites get screwed in portrait orientation, read there only how it happens and why I strongly recommend to use the below media query.

@media handheld,
only screen and (max-width: 767px),
screen and (orientation: portrait) {
    /* ========================================================================= */
    /* ! All phone and tablets(in portrait orientation) specific CSS goes here */
    /* ========================================================================= */

Design Light and Fast Websites

Fast Websites
The CPU of a mobile device is not same as of a desktop computer, thus if we are using a lot of high resolution assets like images and videos, we should give it a second thought from the perspective of mobile devices, also, loading a lot of jQuery/JavaScript for animations and other effects will most likely deteriorate the performance of our website and the website will tend to hang frequently, to overcome this, make sure the website made is light weight and simple, a simple website is definitely a winner for mobile devices as it can also be used easily. Also, we should try reducing requests around network to minimum, some techniques for reducing HTTP requests include using CSS Sprites, combining (and compressing) multiple stylesheets/JavaScript files into one and using Data URI whenever possible. Data URIs are means to inline data in web pages, that is no external HTTP Request, here is one website to encode Data URIs. Back to JS, we should try and load all JavaScript in the end as it will increase the overall performance or at least we can use defer and async attributes (HTML5 only), furthermore, a lot of JS becomes useless for mobile device anyways, we should simply not load them by checking for user agent, here is JS snippet which pretty much checks for every mobile and tablet around:

var mobile = (/iphone|ipod|android|blackberry|opera mini|opera mobi|skyfire|maemo|windows|phone|palm|iemobile|symbian|symbianos|fennec/i.test(navigator.userAgent.toLowerCase()));
var tablet = (/ipad|android 3|sch-i800|playbook|tablet|kindle|gt-p1000|sgh-t849|shw-m180s|a510|a511|a100|dell|streak|silk/i.test(navigator.userAgent.toLowerCase()));
if (mobile) { /* JS for mobile devices */ } else if (tablet) { /* JS for tablets */ } else { /* JS for everything else */ }

This is not a 100% bullet proof method, but there is nothing to lose.

Dealing with Hardware

One thing to remember while building mobile websites is that they don’t have any mouse or keyboard, so all keyboard jQuery for navigation will not work, also, since there is no mouse, there are no hover effects. Building navigation menu for tablets is little tricky, although most tablets like iPad make most of the navigation menus easily usable, however, in some tablets like PlayBook, making our navigation menu work is real pain, especially the ones with sub menus (since they use hover), we need to carefully CSS between :hover and :active pseudo classes (as they are practically same for mobile devices). Whitespacing is another crucial element in mobile devices, we don’t want our website to look in clutter and we must build elements, especially clickable elements with decent amount of padding **and adequate **spacing so that our fingers can tap easily on them (since our fingers are much more thicker than mouse pointers and some times it gets irking when we can not click items and need to zoom-in to do so). Besides, check out jQuery Mobile for adding touch gestures to websites.

Ditch Flash

Most of us are already aware of that many mobile devices like iPhones, iPads, Windows Phones, Chrome on Android, etc don’t have flash, even if some do, flash experience on them is not the same as in desktop computers, thus we should certainly not use it. We can use jQuery animation instead of flash to achieve most of the effects and where flash is absolutely necessary, we can do conditionals to check for flash and then execute the suitable code. SWFObject is an easy to use and standards friendly method to embed Flash content, which utilizes one small JavaScript file, we should use this where we absolutely need to use flash.

And finally, not all tablets are Webkit, use standardized properties!

Windows 8 Tablet
I know this will sound weird to most of you, especially since currently every tablet (probably) is on Webkit and thus what we tend to do is use those non standardized -webkit only CSS3 without their other counterparts, though it is very helpful and it works (and we should use them), but there are problems because of this, let me illustrate one. A decade ago, IE6 was the most dominant web browser in the world, the whole Internet was full of websites made only for IE6, the users of other browsers were discontented. Though that particular problem is over now, but it is back in another form now, Webkit. Webkit is the rendering engine used by almost every modern mobile device (except a very few) and hence the mobile Internet is now full of Webkit only websites, now what if in future tablets ditch Webkit? And that future might not be very distant, later this year, Microsoft will introduce its flagship for tablet operating system, Windows 8, and as far as I can tell from its release preview and beta, its quite good, and its success wont be any surprise, however, it will be a surprise for designers when most of their websites wont work on it’s default web browser. Similarly, Firefox and Opera also have a decent share of mobile browsing, those -webkit properties wont work on even them (although Opera supports some -webkit properties). So to avoid all this, we are better off using standardized CSS properties for most of our designing and use -webkit properties with their -moz, -ms, -o and prefixless counterparts. can help you to make your cross-browser CSS.

Further Reading [unordered_list style=”arrow”]

Best .htaccess Hacks for WordPress

I previously wrote Best .htaccess Hacks For Websites, now this article has .htaccess hacks pertaining to WordPress only. .htaccess is a configuration file on your server which controls Apache Server and is a very powerful tool for your website if used properly. Here are some .htaccess snippets which will surely help you improve your WordPress installation.

Please backup your .htaccess file before doing any changes. In case anything goes unexpected just replace the .htaccess with your backup.

Redirect WordPress Feed to FeedBurner

This simple snippet will redirect your default WordPress feed to your Feedburner, easy yea?

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
RewriteRule ^feed/?([_0-9a-z-]+)?/?$ [R=302,NC,L]

Simpler Login URL

A single line of code .htaccess can give you a better login experience, now you will just need to go to instead of

RewriteRule ^login$ [NC,L]

Protect WordPress Blog from Script Injections

This snippet will protect your WordPress from malicious script injections.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Remove /category/ from your WordPress URL

This will transform to

RewriteRule ^category/(.+)$$1 [R=301,L]

Redirect Day and Name Permalinks to /%postname%/

If you have recently moved from day and name permalink structure to only post name structure, then use this snippet to redirect all backlinks.

RedirectMatch 301 /([0-9]+)/([0-9]+)/([0-9]+)/(.*)$$4

Allow only particular IP address to wp-admin directory

If your blog is only managed by you and you have a static IP, then you can use this snippet to make the admin panel accessible only to your IP address.

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Example Access Control"
AuthType Basic

order allow, deny
deny from all
allow from xx.xx.xx.xx

Protect your WordPress from Hotlinking

Wanna save bandwidth by not serving to other websites? Try the below snippet.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?example\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]