Ultra-Short Link Generation URL: https://2fa.hk/tools/t/shorten.php
Sometimes, an overly long hyperlink address is hard to remember and looks unsightly.
However, the short link generation websites found online either require registration, real-name verification, payment, or they expire shortly after.
Today, I'll teach you a trick to build your own ultra-short link generation page.
To convert a long web link into a short link, you can typically use a URL shortening service. These services generate a shorter URL and point it to the original long link. You can use existing APIs to achieve this function, or implement it by building your own service.
Here are some common methods:
Using Third-Party URL Shortening Services
For example, Google's URL shortener service has been shut down, but you can still use other third-party services such as:
- Bitly: https://bitly.com/
- TinyURL: https://tinyurl.com/
- t2m: https://t2m.io/
These services offer web versions and APIs, allowing you to convert long links into short links.
Implementing Short Link Functionality with PHP
If you want to build your own URL shortening service using PHP code, you can follow these steps:
- Create a database: Used to store the mapping relationship between long URLs and short URLs.
- Generate a short link: Use an algorithm (such as a hash function) to generate a short unique identifier (usually a short string).
- Save data: Store the original URL and the short link identifier in the database.
- Redirect: When the short link is accessed, use a redirect to guide the user to the original URL.
Below is a simplified PHP code example:
<?php
// Connect to database
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "shorten_url";
$conn = new mysqli($host, $username, $password, $dbname);
// Check database connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Function to generate short link
function generateShortLink($longUrl) {
// Create a random short URL identifier (usually a hash algorithm or random generation)
$shortCode = substr(md5($longUrl), 0, 6);
return $shortCode;
}
// Handle request
if (isset($_POST['longUrl'])) {
$longUrl = $_POST['longUrl'];
$shortCode = generateShortLink($longUrl);
// Store in database
$stmt = $conn->prepare("INSERT INTO urls (long_url, short_code) VALUES (?, ?)");
$stmt->bind_param("ss", $longUrl, $shortCode);
$stmt->execute();
// Output short link
echo "Short URL: http://yourdomain.com/" . $shortCode;
}
// Handle short link redirect
if (isset($_GET['code'])) {
$shortCode = $_GET['code'];
$stmt = $conn->prepare("SELECT long_url FROM urls WHERE short_code = ?");
$stmt->bind_param("s", $shortCode);
$stmt->execute();
$stmt->bind_result($longUrl);
$stmt->fetch();
// Redirect to original URL
if ($longUrl) {
header("Location: $longUrl");
} else {
echo "URL not found!";
}
}
?>
Implementing Short Link Functionality with Python
If you prefer Python, you can use code similar to the Flask framework to implement it:
from flask import Flask, request, redirect
import hashlib
import sqlite3
app = Flask(__name__)
# Function to generate short link
def generate_short_link(long_url):
return hashlib.md5(long_url.encode()).hexdigest()[:6]
# Store the relationship between long link and short link
def store_url(long_url, short_code):
conn = sqlite3.connect('urlshortener.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS urls (long_url TEXT, short_code TEXT)')
cursor.execute('INSERT INTO urls (long_url, short_code) VALUES (?, ?)', (long_url, short_code))
conn.commit()
conn.close()
# Handle long link request
@app.route('/shorten', methods=['POST'])
def shorten_url():
long_url = request.form['longUrl']
short_code = generate_short_link(long_url)
store_url(long_url, short_code)
return f"Short URL: http://localhost:5000/{short_code}"
# Handle short link redirect request
@app.route('/<short_code>')
def redirect_to_long_url(short_code):
conn = sqlite3.connect('urlshortener.db')
cursor = conn.cursor()
cursor.execute('SELECT long_url FROM urls WHERE short_code = ?', (short_code,))
row = cursor.fetchone()
conn.close()
if row:
return redirect(row[0])
else:
return "URL not found!"
if __name__ == "__main__":
app.run(debug=True)
Conclusion
- Using ready-made URL shortening services (such as Bitly, TinyURL) is the simplest method.
- If you want to build your own URL shortening service, you can implement it using languages like PHP or Python. The methods are generally the same, mainly accomplished by generating unique identifiers and database storage.
- Use an appropriate hash algorithm (such as MD5) to generate short links, and ensure to look up the corresponding long link when redirecting.
1