ઝડપી ટીપ: PHP ની 10 લાઇન્સ સાથે એક સરળ URL શોર્ટનર બનાવો 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!
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).