1. Go to this page and download the library: Download richardowen/url-shortener library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
UrlShortener\UrlShortener;
use UrlShortener\Storage\FileStorage;
use UrlShortener\Generator\RandomCodeGenerator;
// Create storage and code generator
$storage = new FileStorage(__DIR__ . '/data');
$generator = new RandomCodeGenerator();
// Initialize the URL shortener
$shortener = new UrlShortener($storage, $generator);
// Shorten a URL
$shortCode = $shortener->shorten('https://www.example.com/very/long/url');
echo "Short code: " . $shortCode . "\n";
// Expand the short code
$originalUrl = $shortener->expand($shortCode);
echo "Original URL: " . $originalUrl . "\n";
// Get analytics
$analytics = $shortener->getAnalytics($shortCode);
print_r($analytics);
use UrlShortener\Storage\FileStorage;
$storage = new FileStorage('/path/to/data/directory');
use UrlShortener\Storage\MemoryStorage;
$storage = new MemoryStorage();
use UrlShortener\Storage\DatabaseStorage;
$pdo = new PDO('mysql:host=localhost;dbname=url_shortener', $username, $password);
$storage = new DatabaseStorage($pdo);
use UrlShortener\Generator\RandomCodeGenerator;
$generator = new RandomCodeGenerator(6); // 6 character codes
use UrlShortener\Generator\GeneratorInterface;
class CustomGenerator implements GeneratorInterface
{
public function generate(): string
{
// Your custom logic here
return 'custom-' . uniqid();
}
}
// Get basic analytics
$analytics = $shortener->getAnalytics($shortCode);
// Analytics // - Geographic data (if implemented)