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.
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> original_url.generateShortCode function, which creates a random string from a mix of characters.redirect.php script reads the short code from the URL.shorten.php.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.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.
This guide provides a detailed walkthrough of installing and configuring an Apache web server and…
WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…
I. Project Overview The goal is to automate the process of notifying search engines (like…
1. Database Structure (MySQL) We'll need a database table to store information about our website's…
This explanation aims to provide a solid foundation for understanding the process and implementing your…
Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…