Skip to content

Send a signed link

You can send a link by email that only works for a short time. This program makes such a link and checks it.

<?nvs
// This program makes a download link that works for one hour, and checks it.
// A real server reads its keys from its configuration. This program makes a new one.
array<secret bytes> $keys = [Core\Crypto::generateKey()];
// `signed` returns the address with a `_sig` parameter added. `until` is when the link stops working.
Core\Uri $link = Core\Uri::parse('https://files.example.com/download?file=report.pdf')
->signed({ keys: $keys, until: Core\Time::now()->plus(1h) });
// `verifySignature` throws a `RuntimeError` if the link was changed or is too old.
$link->verifySignature($keys);
echo "the link works\n";
// Somebody changes the file name. The signature no longer matches.
try {
$link->withQueryParameter('file', 'salaries.pdf')->verifySignature($keys);
echo "the changed link works\n";
} catch (RuntimeError $error) {
echo "the changed link does not work\n";
}
Output
the link works
the changed link does not work

signed returns the address with a _sig parameter added. The signature covers the whole address and the time in until. verifySignature throws a RuntimeError when any part of the link was changed, or when the time is over.

Use the same keys to sign and to check. A real server reads them from its configuration, so a link still works after the server restarts.

Read Core\Uri for signed and verifySignature.