Categories
Coding

Ubuntu, PHP, S3, and AWS SDK2 Example

A super quick, super simple little example of how to get started with the AWS SDK2 for PHP. It connects to the S3 service with your credentials and checks to see if a file exists.

  1. Assuming you already have a LAMP setup, you may need to install php-pear:
    sudo apt-get install php-pear
  2. Add the AWS channel and auto discover dependencies:
    pear channel-discover pear.amazonwebservices.com
    pear -D auto_discover=1 install pear.amazonwebservices.com/sdk
  3. Download the .phar file here and throw it on your server in this script’s directory (for this example).
  4. Replace the items in brackets and run the script. The [OBJECT KEY] is just the name of the file, so ‘mypicture.jpg’ in the root of the bucket would have the key ‘mypicture.jpg’.
 <?php

require 'aws.phar';

use Aws\Common\Aws;

$aws = Aws::factory(array(
   'key' => '[KEY HERE]',
   'secret' => '[SECRET HERE]'
));

$client = $aws->get('s3');

echo $client->doesObjectExist('[BUCKET NAME]', '[OBJECT KEY]');

?>

You’ll get back the boolean response of that call (assuming it makes it that far without error). Refer to the API documentation for the other methods and their responses.