logo

Amazon AWS SDK VERSION 2 - PHP with S3

PHP and Amazon S3

Category: Cloud

by designzone

2014-10-11 18:20:56

Server install notes:
From the command-line, you can install the SDK with PEAR as follows (this might need to be run as sudo):
pear config-set auto_discover 1 pear channel-discover pear.amazonwebservices.com pear install aws/sdk

Alternatively, you can combine all three of the preceding statements into one by doing the following:
pear -D auto_discover=1 install pear.amazonwebservices.com/sdk

Once the SDK has been installed via PEAR, you can include the aws.phar into your project with:
require 'AWSSDKforPHP/aws.phar';

This assumes that the PEAR directory is in your PHP include path, which it probably is, if PEAR is working correctly.
If  needed, you can determine your PEAR directory by running pear config-get php_dir.

HEADER STUFF:
/**
 * AMAZON STUFF
 */
require '/usr/share/pear/AWSSDKforPHP/aws.phar';

use Aws\S3\S3Client;

$awsAccessKey = "DGTOxxxxxxxxxx";
$awsSecretKey = "KuIdxxxxxxxxxxxxxxxxxxxxxxxx";

// Instantiate the S3 client with your AWS credentials
$s3 = S3Client::factory(array(
    'key'    => $awsAccessKey,
    'secret' => $awsSecretKey,
));

$bucket="assets.mybuckets.com";

UPLOAD A LOCAL FILE TO S3:
 $localImage = '/tmp/data2.txt';
 $s3->putObject(array(
     'Bucket' => $bucket,
     'SourceFile' => $localImage,
     'Key'        => '2015/07/' . basename($localImage)
 ));

UPLOAD A WEB FILE TO S3:
$fullfilename="http://i621.photobucket.com/albums/tt298/cesar_salad_2009/starbucks-logo.jpg";
$get_month=date('m');
$get_year=date('Y');
$filename="mySubDir/" . $get_year . "/" . $get_month . "/1.jpg";
$binary = file_get_contents($fullfilename);

$s3->putObject(array(
       'Bucket' => $bucket,
       'Key'    => $filename,
       'Body'   => $binary,
       'ContentType' => 'image/jpeg',
       'ACL' => 'public-read'
));

Listing the contents of a bucket:
$result = $s3->listBuckets();

 foreach ($result['Buckets'] as $bucket) {
   // Each Bucket value will contain a Name and CreationDate
   echo "{$bucket['Name']} - {$bucket['CreationDate']}\n";
}

Create a bucket or Folder within a bucket:
$bucket="apple.net/";
$s3->createBucket(array('Bucket' => $bucket));
$bucketwithfolder="apple.net/123/";
$s3->createBucket(array('Bucket' => $bucketwithfolder));

comments powered by Disqus