PHP code example of horde / service_urlshortener

1. Go to this page and download the library: Download horde/service_urlshortener 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/ */

    

horde / service_urlshortener example snippets


use Horde\Service\UrlShortener\TinyUrl;
use Horde\Service\UrlShortener\ValueObject\LongUrl;

// Simple facade API
$shortener = new TinyUrl($httpClient, $requestFactory);
$shortUrl = $shortener->shorten('https://www.example.com/very/long/url');
echo $shortUrl; // https://tinyurl.com/abc123

// Rich domain API with metadata
$longUrl = LongUrl::fromString('https://www.example.com/very/long/url');
$result = $shortener->shortenWithMetadata($longUrl);

echo $result->getShortUrl()->toString();
echo "Saved: {$result->getPercentageSaved()}%";
echo "Reduction: {$result->getLengthReduction()} characters";

use Horde\Service\UrlShortener\ValueObject\ShortenerConfig;

$config = ShortenerConfig::default()
    ->withTimeout(30)
    ->withCustomAlias('myalias')
    ->withExpiration(14); // days

$shortener = new TinyUrl($httpClient, $requestFactory, $config);

shorten(string|UriInterface $url): string

shortenWithMetadata(LongUrl $url): ShorteningResult

use Horde\Service\UrlShortener\UrlShortenerException;

try {
    $shortUrl = $shortener->shorten($longUrl);
} catch (UrlShortenerException $e) {
    // Handle shortening failures
}