Amazon S3 (Simple Storage Service) - Writing Data Objects to Buckets using PHP

This article will give you brief tutorial on writing data objects to buckets on Amazon S3 Servers using PHP code.

Software Requirements:






Below is the PHP Code Snippet that allows you to writing data objects to buckets.

< ?
   require_once 'Crypt/HMAC.php';
   require_once 'HTTP/Request.php';
 
   define ('DATE_RFC822',"D, d M Y G:i:s O");
   define ('S3_URL',"http://s3.amazonaws.com/");
   define ('KEYID',"Amazon KeyId");
   define ('SECRETKEY',"Amazon Secret Key");
   define ('PUT',"PUT");
   define ('CONTENT_TYPE',"File Mime Type");
   define ('PUBLIC_READ',"public-read");
 
   function putObject($bucketname,$key, $method = PUT,$acl = PUBLIC_READ,$filePath, $contentType = CONTENT_TYPE)
   {
     $contentLength = sprintf("%u", filesize($filePath));
     $resource = $bucketname."/".urlencode($key);
     $req =& new HTTP_Request(S3_URL.$resource);
     $req->setMethod($method);
     $httpDate = gmdate("D, d M Y G:i:s T");
     $req->addHeader("Date", $httpDate);
     $req->addHeader("Content-Type", $contentType);
     $req->addHeader("Content-Length", $contentLength);
     $req->addHeader("x-amz-acl", $acl);
 
     $MD5 = hex2b64(md5_file($filePath));
     $req->addHeader("Content-MD5", $MD5);
 
     $req->setBody(file_get_contents($filePath));
     $stringToSign="$methodn$MD5n$contentTypen$httpDatenx-amz-acl:$acln";
     $stringToSign.="/$resource";
     $hasher =& new Crypt_HMAC(SECRETKEY, "sha1");
     $signature = hex2b64($hasher->hash($stringToSign));
     $req->addHeader("Authorization", "AWS " . KEYID . ":" . $signature);
     $req->sendRequest();
     if ($req->getResponseCode() == 200)
     {
         echo "$filePath Object Uploaded Successfully";
     }
     else
     {
         echo "$filePath Object Not Uploaded Successfully";
     }
   }
putObject("bucket name","File Key Name",PUT,PUBLIC_READ,"Uploading File Path",CONTENT_TYPE);
?>

If you see the above code snippet first two lines is compulsory. It tells the PHP to load the CRYPT_HMAC and HTTP_REQUEST library required for uploading files to Amazon Simple Storage Service. After that defined all the constants. Then the putObject function to perform the job of uploading data object to bucket.

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)