How to Create Your Own URL Shortener Website – Step-by-Step Guide 🌐🚀
Creating your own URL shortener website can be a fun and useful project, whether you want to shorten links for personal use, or even start a service for others. With this step-by-step guide, you’ll learn how to build a custom URL shortener from scratch using PHP, MySQL, and JavaScript. Let's get started! 🛠️👨💻
Step 1: Setting Up Your Development Environment 🔧
Before you start coding, you'll need a local server environment to run the website. Here’s how to set it up:
1. Install XAMPP or WAMP
- XAMPP (Cross-Platform Apache MySQL PHP and Perl) or WAMP (Windows, Apache, MySQL, PHP) are easy-to-use software packages that will allow you to run a local server on your computer.
- Download XAMPP from here and install it.
2. Set Up MySQL Database
- Open the phpMyAdmin interface by visiting
http://localhost/phpmyadmin/
in your browser. - Create a new database for your URL shortener (e.g.,
url_shortener
). - Add a table with the following fields:
id
(INT, AUTO_INCREMENT, PRIMARY KEY)original_url
(VARCHAR)shortened_url
(VARCHAR)created_at
(TIMESTAMP)
Step 2: Building the Frontend (HTML & CSS) 🌐
You need a user-friendly page where people can input URLs to shorten. Here’s how to build the basic layout:
1. HTML Structure
Create a file called index.html with the following structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My URL Shortener</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Welcome to My URL Shortener!</h1>
<form action="shorten.php" method="POST">
<label for="url">Enter URL to shorten:</label>
<input type="url" name="url" id="url" required>
<button type="submit">Shorten URL</button>
</form>
<div id="shortened-link"></div>
</div>
</body>
</html>
2. CSS Styling
Create a file called styles.css for basic styling:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
text-align: center;
width: 100%;
max-width: 500px;
}
input[type="url"] {
padding: 10px;
width: 80%;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
margin-top: 10px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
Step 3: Writing PHP Code to Shorten URLs 💻
Now let’s add the logic to shorten the URL using PHP and store it in the database.
1. Shorten URL Logic (shorten.php)
Create a file called shorten.php:
<?php
// Database connection
$host = 'localhost';
$db = 'url_shortener';
$user = 'root';
$pass = '';
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['url'])) {
$original_url = $_POST['url'];
$shortened_url = generateShortenedUrl();
// Insert into database
$sql = "INSERT INTO urls (original_url, shortened_url) VALUES ('$original_url', '$shortened_url')";
if ($conn->query($sql) === TRUE) {
echo "<h2>Your shortened URL is:</h2>";
echo "<a href='$original_url'>$shortened_url</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
function generateShortenedUrl() {
// Random 6-character string
return substr(md5(uniqid(rand(), true)), 0, 6);
}
$conn->close();
?>
Step 4: Creating the Redirect Script 🔄
We need to handle redirection when someone clicks on a shortened URL. This is where we use the shortened_url
to look up the original URL in the database.
1. Redirect Logic (redirect.php)
Create a file called redirect.php:
<?php
// Database connection
$host = 'localhost';
$db = 'url_shortener';
$user = 'root';
$pass = '';
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['code'])) {
$code = $_GET['code'];
$sql = "SELECT original_url FROM urls WHERE shortened_url = '$code'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Redirect to the original URL
$row = $result->fetch_assoc();
header("Location: " . $row['original_url']);
exit();
} else {
echo "URL not found.";
}
}
$conn->close();
?>
Step 5: Testing Your URL Shortener 🚀
- Start the XAMPP/WAMP server and make sure both Apache and MySQL are running.
- Open your browser and visit
http://localhost/your-folder-name/index.html
. - Enter a URL into the form, click “Shorten URL,” and see if the shortened URL appears.
- Clicking the shortened URL should redirect to the original URL.
Step 6: Additional Features & Improvements 🔧
- Custom URL Slugs: Allow users to customize their shortened URL.
- Analytics: Track clicks on shortened URLs by saving additional data (e.g., location, device type).
- Expiration: Set an expiration date for each shortened URL.
- User Authentication: Add user login functionality so users can manage their shortened links.
Conclusion 🌟
Creating a custom URL shortener is a great project to learn about web development. With PHP, MySQL, and a bit of creativity, you can build your own tool for shortening links, and even add extra features like analytics, custom slugs, and expiration dates. 🚀✨
Remember, always focus on user experience and site security while building your application. Once your site is complete, you can monetize it with AdSense if you follow Google’s guidelines for high-quality, original content. 🔑