PHP code example of craftcms / http-message-signatures
1. Go to this page and download the library: Download craftcms/http-message-signatures 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/ */
craftcms / http-message-signatures example snippets
use HttpMessageSignatures\Signer;
use HttpMessageSignatures\Algorithm\HmacSha256;
use GuzzleHttp\Psr7\Request;
// Create a PSR-7 request
$request = new Request(
'POST',
'https://api.example.com/resource',
[
'Host' => 'api.example.com',
'Content-Type' => 'application/json',
'Date' => gmdate('D, d M Y H:i:s \G\M\T'),
],
'{"data":"value"}'
);
// Create signer with HMAC-SHA256 algorithm
$signer = new Signer(new HmacSha256('your-secret-key'));
// Sign the request (returns a new immutable PSR-7 message)
$signedRequest = $signer->sign(
$request,
['@method', '@path', '@authority', 'content-type', 'date'],
[
'keyid' => 'my-key-id',
'signatureId' => 'sig1',
'created' => time(),
'expires' => time() + 300, // Optional: 5 minutes
]
);
// The original request is unchanged (PSR-7 immutability)
// $signedRequest is a new instance with Signature and Signature-Input headers
use HttpMessageSignatures\Verifier;
use HttpMessageSignatures\Algorithm\HmacSha256;
use HttpMessageSignatures\Exception\VerificationException;
$verifier = new Verifier(new HmacSha256('your-secret-key'));
try {
// Verify the signature (returns true if valid)
$isValid = $verifier->verify($signedRequest);
if ($isValid) {
echo "Signature is valid!\n";
}
} catch (VerificationException $e) {
echo "Verification failed: " . $e->getMessage() . "\n";
}
use Http\Factory\Guzzle\RequestFactory;
use HttpMessageSignatures\Algorithm\HmacSha256;
use HttpMessageSignatures\Url\UrlSigner;
use HttpMessageSignatures\Url\UrlSigningConfig;
use HttpMessageSignatures\Url\UrlVerifier;
$algorithm = new HmacSha256('your-secret-key');
$requestFactory = new RequestFactory();
$config = new UrlSigningConfig(
components: ['@target-uri'],
signatureParam: 'signature',
);
$signer = new UrlSigner($algorithm, $requestFactory, $config);
$verifier = new UrlVerifier($algorithm, $requestFactory, $config);
$signedUrl = $signer->sign('https://example.com/image.jpg?w=800');
if ($verifier->verify($signedUrl)) {
echo "URL signature is valid!\n";
}