PHP code example of tilleuls / url-signer-bundle

1. Go to this page and download the library: Download tilleuls/url-signer-bundle 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/ */

    

tilleuls / url-signer-bundle example snippets


// config/bundles.php

return [
    // ...
    CoopTilleuls\UrlSignerBundle\CoopTilleulsUrlSignerBundle::class => ['all' => true],
];

// src/Controller/DocumentController.php
namespace App\Controller;

use CoopTilleuls\UrlSignerBundle\UrlSigner\UrlSignerInterface;

class DocumentController
{
    public function __construct(
        private UrlSignerInterface $urlSigner,
    ) {}
}

// src/Controller/DocumentController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class DocumentController extends AbstractController
{
    private function generateSignedUrl(): string
    {
        // Or $url = $this->generateUrl('secured_document', ['id' => 42], UrlGeneratorInterface::ABSOLUTE_URL);
        $url = $this->generateUrl('secured_document', ['id' => 42]);
        // Will expire after one hour.
        $expiration = (new \DateTime('now'))->add(new \DateInterval('PT1H'));
        // An integer can also be used for the expiration: it will correspond to a number of seconds. For 1 hour:
        // $expiration = 3600;

        // Not passing the second argument will use the default expiration time (86400 seconds by default).
        // return $this->urlSigner->sign($url);

        // Will return a path like this: /documents/42?expires=1611316656&signature=82f6958bd5c96fda58b7a55ade7f651fadb51e12171d58ed271e744bcc7c85c3
        // Or a URL depending on what has been signed before.
        return $this->urlSigner->sign($url, $expiration);
    }
}

// src/UrlSigner/CustomUrlSigner.php
namespace App\UrlSigner;

use CoopTilleuls\UrlSignerBundle\UrlSigner\AbstractUrlSigner;

class CustomUrlSigner extends AbstractUrlSigner
{
    public static function getName(): string
    {
        return 'custom';
    }

    protected function createSignature(string $url, string $expiration, string $signatureKey): string
    {
        return hash_hmac('algo', "{$url}::{$expiration}", $signatureKey);
    }
}