Long URLs can become difficult to manage, especially when sharing them in social platforms. Nowadays sharing your content in social media and similar platforms is more important than publishing it. Otherwise the article will become an orphan in an ocean of content. When sharing an article, the URL should be short as platforms enforce rules for number of characters that can be posted. Now I will walk you through a tutorial on how to create your own tool to shorten a long URL into a concise, easy-to-share link using PHP.
This PHP code performs the following list of actions as part of the URL conversion script.
If you want the code only for the PHP URL shortener tool, the linked article has a simple code without a view count.
The HTML code is for showing a URL shortener form on the page. It has an input field to collect the long URL from the user.
On submitting the form, it sends the long URL to the PHP via a JavaScript AJAX function. This HTML has an output container to show the shortened URL as the AJAX response text.
index.php
<!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>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="form.css">
<style>
table {
max-width: 100%;
border-collapse: collapse;
}
th,
td {
border-bottom: 1px solid #F0F0F0;
padding: 8px;
text-align: left;
max-width: 500px;
}
th {
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div class="phppot-container">
<h1>URL Shortener</h1>
<div id="error" class="error-message"></div>
<form id="urlForm">
<div class="row">
<label for="inputURL">Enter URL: <span class="validation-message"></span></label>
<input type="text" id="inputURL" name="inputURL">
</div>
<div class="row">
<button type="submit">Create Short URL</button>
<div id="loadingIndicator" style="display: none;">Loading....</div>
</div>
</form>
<p id="shortenedURL"></p>
<!--HTML table and Database fetch -->
</div>
<script src="url-convert.js"></script>
</body>
</html>
This URL shortener form page also list the shortened URL code with its original URL and view count.
The table data is dynamic from the database. When creating the short URL the long and short URLs are stored to the database.
This HTML table rows are loaded by iterating the short URL result from the database.
The short URL data is a clickable link. The HTML data table also displays the number of visits happened to the short URL.
index.php
<table>
<thead>
<tr>
<th style="width: 40%;">Original URL</th>
<th style="width: 50%;">Short URL</th>
<th style="width: 10%;">Views</th>
</tr>
</thead>
<tbody>
<?php
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseUrl = $protocol . '://' . $host . $uri . '/';
require_once __DIR__ . '/database_connection.php';
$sql = "SELECT original_url, short_code, views FROM tbl_url_short";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$shortUrl = $baseUrl . $row['short_code'];
?>
<tr>
<td style='width: 200px; word-wrap: break-word;'><?php echo htmlspecialchars($row['original_url']); ?></td>
<td style='width: 50%; word-wrap: break-word;'><a href="<?php echo htmlspecialchars($shortUrl); ?>" target='_blank'><?php echo htmlspecialchars($shortUrl); ?></a></td>
<td style='width: 10%; word-wrap: break-word;'><?php echo htmlspecialchars($row['views']); ?></td>
</tr>
<?php
}
}
$conn->close();
?>
</tbody>
</table>
This JavaScript code sets up an event listener for the URL shortener form submit event.
This script performs the URL validation before processing the AJAX request to the URL shortening endpoint PHP.
The AJAX request is prepared to send the posted long URL to the PHP and receive the short code as a JSON response.
If the response contains the short code, it is considered a success case that shows the short URL in the output container. Otherwise, it will show an error message returned by the PHP.
url-convert.js
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("urlForm").addEventListener("submit", function (event) {
event.preventDefault();
const inputURL = document.getElementById("inputURL").value.trim();
var valid = validateURL(inputURL);
if (!valid) {
return;
}
const errorContainer = document.getElementById("error");
const shortenedURLContainer = document.getElementById("shortenedURL");
var shortCodeInput = Math.floor(Math.random() * 10000);
errorContainer.textContent = "";
errorContainer.style.display = "none";
shortenedURLContainer.textContent = "";
showLoader();
fetch("url_shorterner_endpoint.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ url: inputURL, shortCodeInput: shortCodeInput})
})
.then(response => response.json())
.then(data => {
if (data.shortCode) {
const shortenedURL = window.location.href + data.shortCode;
shortenedURLContainer.innerHTML = `<a href="${shortenedURL}" target="_blank">${shortenedURL}</a>`;
} else {
errorContainer.textContent = "Problem in creating short URL.";
errorContainer.style.display = "block";
}
})
.catch(error => {
errorContainer.textContent = "Problem in creating short URL.";
errorContainer.style.display = "block";
})
.finally(() => {
hideLoader();
});
});
function showLoader() {
...
}
function hideLoader() {
..
}
function validateURL(inputURL) {
..
}
});
The below JavaScript code snippet shows the dependent functions created for the URL shortener JavaScript AJAX code.
The showLoader()
and hideLoader()
are for handling the loading text display during the AJAX processing.
The validateURL()
checks if the long URL is not empty and in the right format. The format validation is tested based on a regex pattern.
url-convert.js
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("urlForm").addEventListener("submit", function (event) {
...
});
function showLoader() {
document.getElementById("loadingIndicator").style.display = "block";
document.querySelector("#urlForm button").style.display = "none";
}
function hideLoader() {
document.getElementById("loadingIndicator").style.display = "none";
document.querySelector("#urlForm button").style.display = "block";
}
function validateURL(inputURL) {
valid = true;
const urlRegex = /^(http|https):\/\/[^ "]+$/;
if (inputURL === "") {
document.querySelector(".validation-message").textContent = "URL is required.";
valid = false;
} else if (!urlRegex.test(inputURL)) {
document.querySelector(".validation-message").textContent = "Please enter a valid URL.";
valid = false;
}
return valid;
}
});
The PHP script receives a long URL posted via the JavaScript AJAX. It validates the format and sanitizes the post-data before processing.
It receives the random alphanumeric short code for the short URL from the AJAX.
url_shorterner_endpoint.php
<?php
require_once __DIR__ . '/database_connection.php';
$data = json_decode(file_get_contents("php://input"));
if (!filter_var($data->url, FILTER_VALIDATE_URL)) {
echo json_encode(array("error" => "Invalid URL"));
exit;
}
$originalURL = $conn->real_escape_string($data->url);
$shortCode = $conn->real_escape_string($data->shortCodeInput);
//URL database insert
?>
Then, it performs a database insert for the original long URL, and short URL mapping.
This PHP script prepares an output encoded as a JSON response with a success or error message. If the database URL insert is not successful, then this code will return an error message to the AJAX callback.
url_shorterner_endpoint.php
$sql = "INSERT INTO tbl_url_short (original_url, short_code) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $originalURL, $shortCode);
if ($stmt->execute()) {
echo json_encode(array("shortCode" => $shortCode));
} else {
echo json_encode(array("error" => "Failed to shorten URL"));
}
$stmt->close();
$conn->close();
This is a PHP page that handles the URL routing. It loads the original URL when the user visits the short URL link.
Each time the user hits the short URL, the .htaccess file redirects to this PHP file.
It increases the view count of the database by redirecting to the original URL.
redirect.php
<?php
require_once __DIR__ . '/database_connection.php';
if(isset($_GET['code'])) {
$shortCode = $_GET['code'];
$sqlUpdate = "UPDATE tbl_url_short SET views = views + 1 WHERE short_code = ?";
$stmtUpdate = $conn->prepare($sqlUpdate);
$stmtUpdate->bind_param("s", $shortCode);
$stmtUpdate->execute();
$stmtUpdate->close();
$sqlSelect = "SELECT original_url FROM tbl_url_short WHERE short_code = ?";
$stmtSelect = $conn->prepare($sqlSelect);
$stmtSelect->bind_param("s", $shortCode);
$stmtSelect->execute();
$resultSelect = $stmtSelect->get_result();
if ($resultSelect->num_rows > 0) {
$row = $resultSelect->fetch_assoc();
$originalUrl = $row['original_url'];
header("Location: $originalUrl");
exit();
} else {
echo "URL not found";
}
$stmtSelect->close();
$conn->close();
} else {
echo "No code provided";
}
?>
.htaccess
RewriteEngine On
RewriteBase /your-project-dir/convert-long-url-to-short/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9a-zA-Z]{6})$ redirect.php?code=$1 [L]