Here's an example of a simple URL shortener using the u-router. This URL shortener will store the original URLs in a SQLite database and generate a unique short code for each URL.
Step 1: Create a SQLite database and a table to store the URLs
Create a new file database.db and run the following SQL query to create a table to store the URLs:
sql
CREATE TABLE urls (
id INTEGER PRIMARY KEY,
original_url TEXT NOT NULL,
short_code TEXT NOT NULL
);
Step 2: Create a PHP script to interact with the database
Create a new file UrlShortener.php with the following code:
php
<?php
class UrlShortener
{
private $db;
public function __construct($dbFile)
{
$this->db = new PDO('sqlite:' . $dbFile);
}
public function shortenUrl($originalUrl)
{
$shortCode = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$stmt = $this->db->prepare('INSERT INTO urls (original_url, short_code) VALUES (:original_url, :short_code)');
$stmt->execute(['original_url' => $originalUrl, 'short_code' => $shortCode]);
return $shortCode;
}
public function getOriginalUrl($shortCode)
{
$stmt = $this->db->prepare('SELECT original_url FROM urls WHERE short_code = :short_code');
$stmt->execute(['short_code' => $shortCode]);
return $stmt->fetchColumn();
}
}
Step 3: Create routes for the URL shortener using u-router
Create a new file index.php with the following code:
php
<?php
require "vendor/autoload.php";
require "UrlShortener.php";
$router = new Cutplane1\URouter();
$urlShortener = new UrlShortener('database.db');
$router->not_found(function() {
http_response_code(404);
echo "<h1>404 Not Found</h1>";
});
$router->middleware(function() {
header('Content-Type: application/json; charset=utf-8');
});
$router->post("/shorten", function() use ($urlShortener) {
$originalUrl = $_POST['url'];
$shortCode = $urlShortener->shortenUrl($originalUrl);
echo json_encode(['short_code' => $shortCode]);
});
$router->get("/<str>", function($shortCode) use ($urlShortener) {
$originalUrl = $urlShortener->getOriginalUrl($shortCode);
if ($originalUrl) {
header('Location: ' . $originalUrl);
exit;
} else {
http_response_code(404);
echo "<h1>404 Not Found</h1>";
}
});
$router->dispatch();
Step 4: Test the URL shortener
You can test the URL shortener by sending a POST request to http://localhost/shorten with the URL you want to shorten in the request body. The response will contain the short code. You can then access the original URL by visiting http://localhost/<short_code>.
Note: This is a very basic URL shortener and does not include any error handling or security measures. You should not use this in production without proper security measures in place.