Store a file on Amazon’s S3 service

s3put.php:
Note: This file requires:
pear install Crypt_HMAC
pear install HTTP_Request

 

#!/usr/bin/php -q
<?php
require_once 'Crypt/HMAC.php';
require_once 'HTTP/Request.php'; // see sample code for note on bug in this package

$bucket = "[a bucket name you already created to store these files]";
$keyId = "[your public key]";
$secretKey = "[your s3 secret key]";
$S3_URL = "https://s3.amazonaws.com/";

$file = $argv[1];
if ( !is_readable($file) )
  die("'$file' is not readable.\nUsage: {$_SERVER['_']} <path_to_file>");

$contentType = "application/binary";
$verb = "PUT";
$httpDate = gmdate("D, d M Y H:i:s T");
$basename = basename($file);
$resource = "$bucket/$basename";
$acl = "private";
$stringToSign = "$verb\n\n$contentType\n$httpDate\nx-amz-acl:$acl\n/$resource";
$hasher =& new Crypt_HMAC($secretKey, "sha1?);
$signature = hex2b64($hasher->hash($stringToSign));

$req =& new HTTP_Request($S3_URL . $resource);
$req->setMethod($verb);
$req->addHeader("content-type", $contentType);
$req->addHeader("Date", $httpDate);
$req->addHeader("x-amz-acl", $acl);
$req->addHeader("Authorization", "AWS " . $keyId . ":" . $signature);
$req->setBody(file_get_contents($file));
$req->sendRequest();

if ($req->getResponseCode() == 200) {
  print "File '$file' was PUT\n";
} else {
  print "An error occured\n";
  exit(1);
  // something bad happened
}

function hex2b64($str) {
  $raw = ";
  for ($i=0; $i < strlen($str); $i+=2) {
    $raw .= chr(hexdec(substr($str, $i, 2)));
  }
  return base64_encode($raw);
}
?>

This was my first stab at this. Better articles are coming soon.

Dave.

Comments are closed.