
Creating a URL shortening script involves several steps, including setting up a database to store shortened URLs, generating unique keys for each URL, and providing redirection from the shortened URL to the original URL. Below is a simple example using PHP and MySQL, along with explanations for each part of the code.
Step 1: Database Setup
First, you need a MySQL database to store the original URLs and their shortened versions. Here’s a simple SQL statement to create a table for this purpose:
CREATE TABLE `url_shortener` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `original_url` VARCHAR(2048) NOT NULL, `short_code` VARCHAR(10) NOT NULL UNIQUE, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Step 2: PHP Script for URL Shortening (shorten.php
)
<?php // Database configuration $host = 'localhost'; // Database host $dbname = 'your_database_name'; // Database name $username = 'your_username'; // Database username $password = 'your_password'; // Database password try { // Create a connection to the database $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("Could not connect to the database: " . $e->getMessage()); } // Shortening logic if (isset($_POST['original_url'])) { $original_url = $_POST['original_url']; // Generate a short code (you can adjust the length here) $short_code = generateShortCode(6); // Insert the original URL and short code into the database $stmt = $pdo->prepare("INSERT INTO url_shortener (original_url, short_code) VALUES (:original_url, :short_code)"); $stmt->execute(['original_url' => $original_url, 'short_code' => $short_code]); // Output the shortened URL $shortened_url = "http://your-domain.com/s/$short_code"; // Adjust the base URL accordingly echo "Shortened URL: " . $shortened_url; } // Function to generate a short code function generateShortCode($length) { return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); } ?>
Step 3: PHP Script for Redirection (redirect.php
)
<?php // Database configuration (same as above) $host = 'localhost'; $dbname = 'your_database_name'; $username = 'your_username'; $password = 'your_password'; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("Could not connect to the database: " . $e->getMessage()); } // Get the short code from the URL if (isset($_GET['code'])) { $short_code = $_GET['code']; // Fetch the original URL from the database $stmt = $pdo->prepare("SELECT original_url FROM url_shortener WHERE short_code = :short_code LIMIT 1"); $stmt->execute(['short_code' => $short_code]); $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result) { // Redirect to the original URL header("Location: " . $result['original_url']); exit; } else { echo "URL not found."; } } ?>
Step 4: HTML Form for Input (index.html
)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>URL Shortener</title> </head> <body> <h1>URL Shortener</h1> <form action="shorten.php" method="POST"> <input type="url" name="original_url" placeholder="Enter your URL here" required> <button type="submit">Shorten URL</button> </form> </body> </html>
Explanation of the Code
- Database Connection:
- We use PDO to connect to the MySQL database, ensuring that errors in connection are handled gracefully.
- Shortening Logic:
- The script checks if the form has submitted an
original_url
. - It generates a unique short code using the
generateShortCode
function, which creates a random string from a mix of characters. - The original URL and its corresponding short code are then inserted into the database.
- The script checks if the form has submitted an
- Redirection Logic:
- When a user accesses the shortened URL, the
redirect.php
script reads the short code from the URL. - It queries the database for the original URL associated with that short code and then redirects the user to the original URL.
- When a user accesses the shortened URL, the
- Form HTML:
- A simple HTML form allows users to input the URL they want to shorten. It submits the data to
shorten.php
.
- A simple HTML form allows users to input the URL they want to shorten. It submits the data to
Important Considerations
- Validation: You might want to add additional validation for the URLs entered by users to ensure they are well-formed and reachable.
- Collision Handling: This simple implementation does not handle potential collisions for
short_code
. You would want to check if a generated short code already exists in the database and generate a new one if it does. - Security: For production applications, consider additional security measures (e.g., prepared statements to prevent SQL injection).
- Deployment: Adjust the base URL (
http://your-domain.com/s/$short_code
) according to your live server’s settings.
This basic URL shortener gives you a solid foundation to build upon, allowing you to include features like analytics, expiration of links, and user management if needed.