Create Your Own URL Shortener with This Simple Code
Are you tired of sharing long, cumbersome URLs with others? Do you want to create your own custom shortened links? Look no further! In this post, we'll show you how to create your own URL shortener using a simple code.
The Code:
You can use the following PHP code to create a basic link shortener:
// Configuration
$base_url = "http://yourdomain.com"; // Your domain name
$db_name = "links"; // Database name
$db_user = "root"; // Database username
$db_pass = ""; // Database password
// Connect to database
$conn = mysqli_connect("localhost", $db_user, $db_pass, $db_name);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Function to shorten URL
function shorten_url($url) {
global $conn;
$url = mysqli_real_escape_string($conn, $url);
$query = "INSERT INTO links (url) VALUES ('$url')";
mysqli_query($conn, $query);
$id = mysqli_insert_id($conn);
$short_url = $base_url . "/" . $id;
return $short_url;
}
// Function to redirect to original URL
function redirect_url($id) {
global $conn;
$query = "SELECT url FROM links WHERE id = '$id'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$url = $row['url'];
header("Location: $url");
exit;
}
// Handle URL shortening and redirection
if (isset($_POST['url'])) {
$url = $_POST['url'];
$short_url = shorten_url($url);
echo "Shortened URL: $short_url";
} elseif (isset($_GET['id'])) {
$id = $_GET['id'];
redirect_url($id);
}
// Close database connection
mysqli_close($conn);
?>
How to Use:
Create a new PHP file and paste the code into it.
Replace the configuration variables with your own values.
Create a database and table to store the links.
Upload the file to your server.
To shorten a URL, send a POST request to the file with the URL as a parameter.
To redirect to the original URL, send a GET request to the file with the shortened URL's ID as a parameter.
Note: This is a basic example and may not be suitable for production use without additional security measures.
0 Comments