PHP code example of code4nix / uri-signer

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

    

code4nix / uri-signer example snippets




declare(strict_types=1);

namespace App\Controller;

use Code4Nix\UriSigner\Exception\ExpiredLinkException;
use Code4Nix\UriSigner\Exception\InvalidSignatureException;
use Code4Nix\UriSigner\Exception\MalformedUriException;
use Code4Nix\UriSigner\UriSigner;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/uri_signer_test", name="uri_signer_test")
 */
class UriSignerTestController extends AbstractController
{

    public function __construct(
        private readonly UriSigner $uriSigner,
    ) {
    }

    public function __invoke(Request $request): Response
    {
        // Sign a URI with an expiration time of 10 min
        $uri = 'https://foo.bar/test';

        //https://foo.bar/test?_hash=eyJoYXNoZWQiOiJqNXUxeE1NRnpTRU1yRnREc
        $signedUri = $this->uriSigner->sign($uri, 600);

        // For test usage we will create our request object manually.
        $request = Request::create(
            $signedUri,
        );

        $responseText = 'URI is valid.';

        // Use check($signedUri, true) or checkRequest($request, true)
        // If set to true the second boolean parameter will raise exceptions if a URI cannot be verified.
        try {
            $this->uriSigner->checkRequest($request, true); // or $this->uriSigner->check($signedUri, true);
        } catch (MalformedUriException $e) {
            $responseText = 'Malformed URI detected!';
        } catch (ExpiredLinkException $e) {
            $responseText = 'URI has expired!';
        } catch (InvalidSignatureException $e) {
            $responseText = 'Invalid signature detected! The URI could have been tampered.';
        } catch (\Exception $e) {
            $responseText = 'Oh, la, la! Something went wrong ;-(';
        }

        return new Response($responseText);
    }
}