CloudFront Signed URLs in PHP

Sample Code & Libraries>CloudFront Signed URLs in PHP
Community Contributed Software

  • Amazon Web Services provides links to these packages as a convenience for our customers, but software not authored by an "@AWS" account has not been reviewed or screened by AWS.
  • Please review this software to ensure it meets your needs before using it.

This PHP function will create a signed URL with a canned policy for serving CloudFront private content.


Submitted By: milessvi
AWS Products Used: Amazon CloudFront
Language(s): PHP
License: Common Public License
Created On: February 10, 2010 2:55 PM GMT
Last Updated: August 16, 2010 5:37 PM GMT

To use this function pass it the resource url, and the amount of time the url will be active for. To create a custom policy signed url, you will have to modify the function slightly to add a url safe policy.

For example the following will create a signed url that is active for 60 seconds:

$url = getSignedURL("", 60);

function getSignedURL($resource, $timeout)
	//This comes from key pair you generated for cloudfront

	$expires = time() + $timeout; //Time out in seconds
	$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';		
	//Read Cloudfront Private Key Pair

	//Create the private key
	$key = openssl_get_privatekey($priv_key);
		echo "<p>Failed to load private key!</p>";
	//Sign the policy with the private key
	if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
		echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
	//Create url safe signed policy
	$base64_signed_policy = base64_encode($signed_policy);
	$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

	//Construct the URL
	$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;
	return $url;
©2017, Amazon Web Services, Inc. or its affiliates. All rights reserved.