Build your own URL to shorten

Source: Internet
Author: User
Most of us are familiar with this website bit. ly or t. co our Twitter or Facebook feed. These are short URLs. this is a short alias or an example of pointing to a long page link. For example, I can shorten the URL http://bit.ly/saayw5 to send you a long url, and Google iron the search result. This will be easier

Most of us are familiar with this website bit. ly or t. co our Twitter or Facebook feed. These are short URLs. this is a short alias or an example of pointing to a long page link. For example, I can give you a shortened URL http://bit.ly/SaaYw5 that will forward you to a long URL, Google on how to ironed the shirt's search results. It will be easier to text 20 characters in bit. ly url to your son, who is at college and preparing for his first big job interview.

In this article, you will learn how to create a fully functional URL to shorten your website, and whether to use the front-end controller/framework or not. If you are using a front-end controller, I will discuss how to easily integrate this URL shortening without going deep into controller programming.

Answer some common questions

Therefore, with bit. ly and many other URLs shorteners like its existence and can be viewed freely, why bother building our own? Most shortening services even have an easy-to-use API that allows us to generate a shortened URL through programming, which is used in our PHP script.

The best reason is for convenience, beauty, and brand awareness. For example, if your website has a large number of reports, a very active blog or a large album application, there will be a lot of links. A url splitter allows you to create it programmatically and send it to your readers by email or publish it on your website with a clean and simple link. The most obvious advantage is that your readers have instant brand awareness and your website.

You may want to know why you always see a letter, in the shortening of the Web site's digital mix. By having more than 10 options (0-9) each number, we can have more significant combinations while keeping the code as short as possible.

The characters we will use include numbers 1-9 and various uppercase/lowercase letters. I have deleted all vowels to prevent them from creating links which is unexpectedly bad if I have deleted any characters that may be confused with each other. This gives us a list of about 50 characters that can be used for each number. This means that we use two characters, we have 2500 possible combinations, and 125,000 of the possibilities are three characters, up to 6.5 million of the combinations have only four big words!

Planning database

Let's create a short_urls table. This is a simple table and the following create statement is found:

1234567891011 Create table if not exists short_urls (id integer unsigned not null AUTO_INCREMENT, long_url VARCHAR (255) not null, short_code VARBINARY (6) not null, DATE_CREATED integer unsigned not null, counter integer unsigned not null default '0', primary key (ID), mainly short_code (short_code) ENGINE = InnoDB;

We have our standard auto-incrementing complete URLs for primary keys and fields, URL-shortening code (faster index retrieval), and timestamp for creating rows, and the number of times that short Web sites have been browsed.

Note that the long_url field contains a maximum length of 255 characters, which should be sufficient for most applications. If you need to store a long URL, you need to change its definition to TEXT.

Now to PHP!

Create a URL short code

The code for creating and decoding the short URL encoding will be in a class named signed URL. First, let's look at the code responsible for creating short code:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 <? PHP class URLs {protect static $ Characters = "static"; protect static $ Table = "short_urls"; protect static $ checkUrlExists = TRUE; protect $ PDO; protect $ timestamp; common functions _ construct (PDO $ PDO) {$ Ben-> PDO = $ PDO; $ Ben-> timestamp = $ _ SERVER ["REQUEST_TIME"];} public feature urlToShortCode ($ URL) {if (null ($ URL) {throws a new exception ("No URL provided by the URL." );} If ($ this-> validateUrlFormat ($ URL) = FALSE) {a new exception is thrown ("the URL does not have a valid format ." );} If (self-employed: $ checkUrlExists) {if (! $ This-> verifyUrlExists ($ URL) {throws a new exception ("the URL does not exist .") ;}}$ Simple code = $ this-> urlExistsInDb ($ URL); if ($ simple code = FALSE) {$ simple code = $ this-> createShortCode ($ URL );} return $ simple code;} protection function validateUrlFormat ($ URL) {return filter_var ($ URL, FILTER_VALIDATE_URL, expiration);} protection function verifyUrlExists ($ URL) {$ CH = curl_init (); in curl_setopt ($ channel, CURLOPT_URL, $ URL); in curl_setopt ($ channel, CURLOPT_NOBODY, true); in curl_setopt ($ channel, CURLOPT_RETURNTRANSFER, true); curl_exec ($ CH ); $ response = curl_get Info ($ channel, CURLINFO_HTTP_CODE); curl_close ($ CH); return (! Blank ($ response) & $ response = 404 !);} Protection function urlExistsInDb ($ URL) {$ query = "select short_code FROM ". Self: $ table. "WHERE long_url =: long_url LIMIT 1"; $ stmt = $ this-> PDO-> prepare ($ query ); $ PARAMS = array ("long_url" => $ URL); $ stmt-> execution ($ PARAMS); $ result = $ stmt-> fetch () method; return (null ($ result ))? False: $ result ["short_code"];} protection function createShortCode ($ URL) {$ ID = $ this-> insertUrlInDb ($ URL ); $ = $ this-> convertIntToShortCode ($ ID); $ -> insertShortCodeInDb ($ ID, $ ); $ ;} protection function insertUrlInDb ($ url) {$ query = "insert ". Self: $ table. "(Long_url, DATE_CREATED )". "VALUES (: long_url,: timestamp)"; $ hour NT = $ this-> PDO-> prepare ($ query ); $ PARAMS = array ("long_url" => $ URL, "timestamp" => $ this-> timestamp); $ sort NT-> Execute ($ PARAMS ); return $ this-> PDO-> lastInsertId ();} protection function convertIntToShortCode ($ number) {$ ID = INTVAL ($ number); if ($ number <1) {throw a new exception ("Is this ID a valid integer?");} $ Length = strlen (self: $ character ); // ensure that the available characters are at least // there must be a reasonable minimum-there should be // at least 10 characters if ($ length <10) {throw a new exception ("The character length is too small");} $ Code = ""; and ($ No.> $ length-1) {// judge The value of a higher character // In the short-term code should be with the front $ Code = self: $ character [FMOD ($ ID, $ length)]. $ Code; // reset $ id to convert the remaining value $ ID = floor ($ id/$ length);} $ id // the remaining value is less than the length // self :: $ Character $ Code = self: $ character [$ ID]. $ Code; $ Code returned;} protection function insert‑codeindb ($ ID, $ Code) {if ($ id = NULL | $ code = NULL) {a new exception is thrown ("the input parameter (S) is invalid." );} $ Query = "UPDATE ". Self: $ table. "SET short_code =: short_code where id =: ID"; $ response NT = $ this-> PDO-> prepare ($ query ); $ PARAMS = array ("short_code" => $ Code, "ID" => $ number); $ prepare NT-> Execute ($ PARAMS ); if ($ rows NT-> rowCount, etc. () <1) {throws a new exception ("The row is not updated and the short code." );} Returns true ;}...

When we instantiate the signed URL class, we will use its PDO object instance. The Constructor stores this reference and sets the $ timestamp member.

The urltoencode code () method we call is passed to it, and we want to shorten the long URL. This method is encapsulated to create the code for the short url. we will append everything we need to our domain name.

UrlToShortCode () calls validateUrlFormat (). it simply uses the PHP filter to ensure that the URL is correctly formatted. Then, if the static variable $ checkUrlExists is true, verifyUrlExists () will be called. it uses the curly link URL and ensures that it does not return a 404 (not found) error. You can check a 200 (OK) status, but this may cause problems. if the page is accidentally returned, a 301 (move) or 401 (not

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.