Skip to content

Commit 2c20da3

Browse files
committed
Adds example for generating Cloud CDN Signed URLs
Example implementation of generating URL signature for Cloud CDN. Based on: https://cloud.google.com/cdn/docs/using-signed-urls#creating_signed_urls
1 parent 12ea819 commit 2c20da3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

cdn/signUrl.php

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
/*
3+
* Copyright 2018 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
# [START signed_url]
19+
/**
20+
* Creates signed URL for Google Cloud CDN
21+
* Details about order of operations: https://cloud.google.com/cdn/docs/using-signed-urls#creating_signed_urls
22+
*
23+
* @param string $url URL of the endpoint served by Cloud CDN
24+
* @param string $keyName Name of the signing key added to the Google Cloud Storage bucket or service
25+
* @param string $key Signing key as base64 encoded string
26+
* @param int $expiration_time Expiration time as a UNIX timestamp (GMT, e.g. time())
27+
*/
28+
function signUrl($url, $keyName, $key, $expiration_time)
29+
{
30+
// Decode the key
31+
$decoded_key = base64_decode($key, true);
32+
33+
// Determine which separator makes sense given a URL
34+
$separator = (strpos($url, '?') === false) ? '?' : '&';
35+
36+
// Concatenate url with expected query parameters Expires and KeyName
37+
$url = "{$url}{$separator}Expires={$expiration_time}&KeyName={$keyName}";
38+
39+
// Sign the url using the key and encode the signature using base64
40+
$signature = hash_hmac('sha1', $url, $decoded_key, true);
41+
$encoded_signature = base64_encode($signature);
42+
43+
// Concatenate the URL and encoded signature
44+
return "{$url}&Signature={$encoded_signature}";
45+
}
46+
// [END signed_url]
47+
48+
// Example function call (In production store the key safely with other secrets)
49+
$base64_key = '4RfgBoqmotRolLCtU-82Ew=='; // head -c 16 /dev/urandom | base64 | tr +/ -_
50+
$signed_url = signUrl('https://example.com/foo', 'MY-KEY', $base64_key, time() + 1800);
51+
echo $signed_url."\n";

0 commit comments

Comments
 (0)