Skip to content

Instantly share code, notes, and snippets.

@ikeogu
Forked from paulferrett/urlsigning.php
Created November 26, 2021 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikeogu/3c36b259967b9954ad1bce2cf0fed9f8 to your computer and use it in GitHub Desktop.
Save ikeogu/3c36b259967b9954ad1bce2cf0fed9f8 to your computer and use it in GitHub Desktop.
Simple URL signing helper class written in PHP. Use this to generate and verify signed URLs with a shared secret.
<?php
/**
* Url Signing Helper Class
*
* @author Paul Ferrett <paul.ferrett@servicecentral.com.au>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class UrlSigning {
/**
* Sign a URL
*
* @param string $url
* @param string $private_key
* @param string $param_name
* @return string Signed URL
*/
public static function getSignedUrl($url, $private_key, $param_name = 'signature') {
$join = parse_url($url, PHP_URL_QUERY) ? '&' : '?';
return $url . $join . $param_name . '=' . self::getUrlSignature($url, $private_key);
}
/**
* Get the signature for the given URL
*
* @param string $url
* @param string $private_key
* @return string URL signature string
*/
public static function getUrlSignature($url, $private_key) {
return md5($url . ':' . $private_key);
}
/**
* Check that the given URL is correctly signed
*
* @param string $url
* @param string $private_key
* @param string $param_name
* @return bool True if URL contains valid signature, false otherwise
*/
public static function verifySignedUrl($url, $private_key, $param_name = 'signature') {
$param_name = preg_quote($param_name);
if(!preg_match($regex = "/(:?&|\?)?{$param_name}=([0-9a-f]{32})/", $url, $matches)) {
return false;
}
// Get the signature param
$passed_sig = $matches[1];
// Strip signature from the given URL
$url = preg_replace($regex, '', $url);
// Check that the given signature matches the correct one
return self::getUrlSignature($url, $private_key) === $passed_sig;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment