Skip to content

Instantly share code, notes, and snippets.

@fakegit
Forked from paulferrett/urlsigning.php
Created May 22, 2016 07:02
Show Gist options
  • Save fakegit/03b1d2bc5f58fd11f0a1a6f0c54317f0 to your computer and use it in GitHub Desktop.
Save fakegit/03b1d2bc5f58fd11f0a1a6f0c54317f0 to your computer and use it in GitHub Desktop.

Revisions

  1. @paulferrett paulferrett revised this gist Aug 23, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion urlsigning.php
    Original file line number Diff line number Diff line change
    @@ -42,7 +42,7 @@ public static function getUrlSignature($url, $private_key) {
    */
    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)) {
    if(!preg_match($regex = "/(:?&|\?)?{$param_name}=([0-9a-f]{32})/", $url, $matches)) {
    return false;
    }

  2. @paulferrett paulferrett created this gist Aug 23, 2013.
    58 changes: 58 additions & 0 deletions urlsigning.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    <?php

    /**
    * Url Signing Helper Class
    *
    * @author Paul Ferrett <[email protected]>
    * @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;
    }
    }