CloudFront Signed URLs in PHP

Sample Code & Libraries>CloudFront>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.

Details

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("http://abcdefg.cloudfront.net/test.jpg", 60);

function getSignedURL($resource, $timeout)
{
	//This comes from key pair you generated for cloudfront
	$keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

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

	//Create the private key
	$key = openssl_get_privatekey($priv_key);
	if(!$key)
	{
		echo "<p>Failed to load private key!</p>";
		return;
	}
	
	//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>';
		return;
	}
	
	//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;
}
©2014, Amazon Web Services, Inc. or its affiliates. All rights reserved.