How to Make a URL Shortener in PHP?

9 minutes read

URL shortener services are online tools or platforms that are designed to reduce the length of long URLs or web addresses. These services essentially take a long URL inputted by a user and generate a shorter, more compact version of the same URL. The purpose of this process is mainly to make URLs more user-friendly, easy to remember, and shareable.


URL shorteners work by redirecting the shortened URL to the original, longer URL. When a user clicks on the shortened link, they are automatically redirected to the intended webpage. This redirection process is transparent to the user and happens within just a few milliseconds.


Apart from creating shorter URLs, URL shortener services often provide additional features and analytics. These may include tracking the number of clicks on a specific shortened link, providing information about the geographic location of visitors, and monitoring the referral sources.


URL shorteners are widely used for various purposes, such as:

  1. Social Media Sharing: Shortening URLs can be useful on platforms like Twitter, where character limits are often imposed. By shortening URLs, users can effectively share links while conserving precious characters.
  2. Digital Marketing: URL shorteners are popular among marketers as they allow them to track the performance and effectiveness of different marketing campaigns and initiatives.
  3. Memorability: Short URLs are easier to remember and share with others, especially in cases where the original URL may be complex or convoluted.
  4. Aesthetics: Lengthy URLs can look messy or unappealing, especially in printed materials. By shortening URLs, companies can maintain a cleaner and more visually appealing brand image.


It is worth noting that while URL shortening services offer convenience and utility, they also pose potential risks. Due to the opaque nature of these services, users may not always know the final destination of the shortened URL they are clicking on. Malicious individuals may exploit this lack of transparency by disguising harmful or phishing links behind shortened URLs. It's important for users to exercise caution and ensure they trust the source of any shortened links they encounter.

How to make a URL shortener in PHP?

To create a URL shortener in PHP, you can follow these steps:

  1. Create a database table: Start by creating a database table to store the long URLs and their corresponding short codes. The table should contain columns for the long URL and the short code. CREATE TABLE `urls` ( `id` int(11) NOT NULL AUTO_INCREMENT, `long_url` text NOT NULL, `short_code` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `short_code` (`short_code`), KEY `long_url` (`long_url`(100)) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
  2. Create the form: Design a basic HTML form where users can input the long URL they want to shorten. URL Shortener
  3. Create the PHP script to process the form submission: Create a PHP script that handles the form submission, generates a unique short code, and stores the long URL and short code in the database. $shortURL"; } else { echo "Error: " . mysqli_error($db); } } // Function to generate a unique short code function generateShortCode() { $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $shortCode = ''; $length = 6; for ($i = 0; $i < $length; $i++) { $randomIndex = mt_rand(0, strlen($characters) - 1); $shortCode .= $characters[$randomIndex]; } return $shortCode; } ?>
  4. Redirect users from the short URL to the original URL: Create a PHP script that will handle the redirection from the short URL to the original URL. 0) { // Redirect to the long URL $row = mysqli_fetch_assoc($result); $longURL = $row['long_url']; header("Location: $longURL"); exit; } else { echo "Invalid short code."; } ?>
  5. Create a database connection file: Lastly, create a file to establish the database connection using the mysqli extension.


Remember to update the database credentials in the connection file (db_connect.php) with your own details.

Best URL Shortener Services ofSeptember 2024

1
TinySRC

Rating is 5 out of 5

TinySRC

2
Bitly

Rating is 4.9 out of 5

Bitly

3
TinyURL

Rating is 4.8 out of 5

TinyURL

4
Rebrandly

Rating is 4.8 out of 5

Rebrandly

How to get true address of a shortened URL in PHP?

To get the true address of a shortened URL in PHP, you can make use of URL redirection. Here's an example of how you can achieve this using cURL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20

function getTrueURL($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_exec($ch);
    $trueURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    curl_close($ch);

    return $trueURL;
}

$shortenedURL = "http://bit.ly/2XobazT";
$trueURL = getTrueURL($shortenedURL);
echo "True URL: ".$trueURL;


In the above example, the getTrueURL function accepts a shortened URL as a parameter. It sets appropriate cURL options such as CURLOPT_FOLLOWLOCATION to follow any redirections and CURLOPT_MAXREDIRS to limit the number of redirections to 10.


It then executes the cURL request using curl_exec and retrieves the final URL after all the redirections using curl_getinfo with CURLINFO_EFFECTIVE_URL option.


Finally, the returned true URL is echoed out. You can replace the $shortenedURL variable with any shortened URL you have, and the function will return its true address.

How to make a URL shortener in PHP using tinysrc-php-sdk?

To make a URL shortener in PHP using tinysrc-php-sdk, follow the steps below:

  1. Install the tinysrc-php-sdk library: composer require tiny-src/tinysrc-php-sdk
  2. Create a new PHP file, for example, shorten.php.
  3. Import the necessary classes and functions:
  4. Set up the necessary variables and initialize the Tinysrc SDK client: $apiKey = 'YOUR_API_KEY'; $linkToShorten = 'https://www.example.com'; $tinysrc = new Tinysrc($apiKey); Replace 'YOUR_API_KEY' with your actual Tinysrc API key.
  5. Create a ShortenLinkRequest object and set the link you want to shorten: $request = new ShortenLinkRequest($linkToShorten);
  6. Use the Tinysrc client to send the request and get the shortened link: $response = $tinysrc->shortenLink($request); $shortenedLink = $response->getShortenedLink();
  7. Print or use the shortened link as desired: echo "Shortened Link: $shortenedLink"; Note that you can store this shortened link in a database or use it further in your application.
  8. Save and run the PHP file: php shorten.php


That's it! You have successfully created a URL shortener using the tinysrc-php-sdk library in PHP.

Best Web Hosting for PHP and MySQL in September 2024

1
DigitalOcean

Rating is 5 out of 5

DigitalOcean

2
AWS

Rating is 4.9 out of 5

AWS

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways

Facebook Twitter LinkedIn Telegram Whatsapp

Related Posts:

Shorten URL services are online platforms or tools that allow users to make long URLs shorter without affecting the destination. These services mainly aim to make URLs more convenient to share, especially on platforms with character limits like social media pl...
Migrating from PHP to Java is a process of porting an existing application written in PHP to Java programming language. While both PHP and Java are popular programming languages for building web applications, migrating from PHP to Java may be necessary due to ...
To add either &#34;http://&#34; or &#34;https://&#34; to a Swift URL as a string without using list items, you can follow these steps:Create a variable to store the URL string: var urlString = &#34;example.com&#34; Use conditional statements to check if