alasdairkeyes/redirecttoken

Package to generate tokens for validating redirections

1.0.0 2018-12-18 10:39 UTC

This package is not auto-updated.

Last update: 2024-04-18 10:39:53 UTC


README

pipeline status coverage report Latest Version on Packagist Total Downloads

redirecttoken

PHP Package to generate tokens for validating redirections

Description

Track clicks to external links on your site by linking to a local file that handles redirection.

From

<a href="https://someothersite.com/">Click me</a>
<a href="/redirect?uri=<remoteurl>&token=<validationtoken>">Click me</a>

This package provides the means to generate a validation token so that unscrupulous bots don't use your redirect as a redirect for nefarious means.

Installation

  • Add the paclage to composer with the following
    composer require alasdairkeyes/redirecttoken
    

Example

Generate Token for URL to redirect

    # Or any other Class that implements Psr\Http\Message\UriInterface
use GuzzleHttp\Psr7\Uri;
use RedirectToken\Generator;

$secretKey = 'fgsdkjghsekugkserg';
$uriDestination = new Uri('https://www.google.co.uk/');

// Instantiate token generator and create token
$generator = new Generator($secretKey);
$token = $generator->generateToken($uriDestination);

$validRedirectUri = 'redirect.php?' . http_build_query([ 'uri' => (string)$uriDestination, 'token' => $token ], '', '&');

// Output
print '<a href="' . $validRedirectUri . '">Valid redirect</a>' . PHP_EOL;

Validate Token

    # Or any other Class that implements Psr\Http\Message\UriInterface
use GuzzleHttp\Psr7\Uri;
use RedirectToken\Validator;

// Parse the URI Query
parse_str($_SERVER["QUERY_STRING"], $q);

$redirectUri = new Uri($q['uri']);
$token = $q['token'];

// Instantiate validator
$validator = new Validator($secretKey);

if ($validator->validateUriToken($redirectUri, $token)) {
    header('Location: ' . $redirectUri, true, 302);
} else {
    print "Invalid request";
}

Prebuilt

If you've cloned the repository, you can test with PHP's builtin webserver

cd example
php -S localhost:8080

Goto localhost:8080 in a web browser

Changelog

  • 2018-12-18 :: 1.0.0 :: Move to stable release
  • 2017-10-29 :: 0.1.0 :: First Release

Site

https://gitlab.com/alasdairkeyes/redirecttoken

Author

License

Released under GPL V3 - See included license file.