Advertisement
  1. Code
  2. Cloud & Hosting
  3. AWS

Programming With Yii2: Using Amazon S3

Scroll to top
Read Time: 8 min
This post is part of a series called How to Program With Yii2.
How to Program With Yii2: Google Authentication
Programming With Yii2: Routing and URL Creation
Final product imageFinal product imageFinal product image
What You'll Be Creating

If you're asking, "What's Yii?" check out my earlier tutorial, Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released in October 2014.

In this Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. In today's tutorial, I'll walk you through the basics of browsing, uploading and downloading files to and from Amazon's cloud-based S3 storage service. Essentially, I've created a simple storage model and controller as examples which you can extend for your needs.

Just a reminder, I do participate in the comment threads below. I'm especially interested if you have different approaches, additional ideas, or want to suggest topics for future tutorials. If you have a question or topic suggestion, please post below. You can also reach me on Twitter @reifman directly.

What's Amazon S3?

Amazon S3 provides easy-to-use, advanced cloud-based storage for objects and files. It offers 99.99% availability and 99.999999999% durability of objects.

It offers a variety of features for simple or advanced usage. It's commonly used as the storage component for Amazon's CDN service CloudFront, but these are distinct and can be used independently of each other.

You can also use S3 to migrate files over time to archive in Amazon Glacier, for added cost savings.

Like most all of AWS, you operate S3 via APIs, and today, I'm going to walk you through browsing, uploading and downloading files from S3 with Yii.

Getting Started

To run the demonstration code, you'll need your own Amazon AWS account and access keys. You can browse your S3 tree from the AWS console shown below:

Yii AWS S3 - AWS Console MenuYii AWS S3 - AWS Console MenuYii AWS S3 - AWS Console Menu

S3 consists of buckets which hold numerous directories and files within them. Since I used to use AWS as a CDN, my WordPress tree remains in my old bucket. You can browse your bucket as well:

Yii AWS S3 - BucketsYii AWS S3 - BucketsYii AWS S3 - Buckets

As I traverse the tree of objects, here's a deeper view of my bucket contents:

Yii AWS S3 - Objects Folders and FilesYii AWS S3 - Objects Folders and FilesYii AWS S3 - Objects Folders and Files

Programming With S3

Again, I'll build on the hello tree from GitHub for our demonstration code (see the link on this page.) It's derived from Yii2 basic.

Obtaining Your Access Keys

You will need access keys for the AWS S3 API if you don't already have them. If not, you can get them by browsing to Security Credentials and creating a new pair:

Yii AWS S3 - Security Credentials and Access KeysYii AWS S3 - Security Credentials and Access KeysYii AWS S3 - Security Credentials and Access Keys

For our code demonstration, you'll need to place them in your hello.ini file with other secure keys and codes:

1
$ more /var/secure/hello.ini 
2
mysql_host="localhost"
3
mysql_db="hello"
4
mysql_un="tom_mcfarlin"
5
mysql_pwd="is-never-gonna-give-up-rick-astley"
6
aws_s3_access = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXA"
7
aws_s3_secret = "nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXb"
8
aws_s3_region = "us-east-1"

Installing the Yii Extension for AWS

For this tutorial, we'll use Federico Motta's AWS extension for Yii2. He's definitely the youngest Yii programmer whose code I've used for an Envato Tuts+ tutorial:

Yii AWS S3 - AWS SDK Extension for Yii2 on GithubYii AWS S3 - AWS SDK Extension for Yii2 on GithubYii AWS S3 - AWS SDK Extension for Yii2 on Github

Isn't it amazing how quickly kids are picking up programming these days?

Here's the installation process using composer:

1
$ composer require fedemotta/yii2-aws-sdk
2
Using version ^2.0 for fedemotta/yii2-aws-sdk
3
./composer.json has been updated
4
Loading composer repositories with package information
5
Updating dependencies (including require-dev)
6
  ...
7
  
8
  - Installing aws/aws-sdk-php (3.18.27)
9
    Downloading: 100%         
10
11
  - Installing fedemotta/yii2-aws-sdk (v2.0)
12
    Loading from cache
13
14
aws/aws-sdk-php suggests installing aws/aws-php-sns-message-validator (To validate incoming SNS notifications)
15
aws/aws-sdk-php suggests installing doctrine/cache (To use the DoctrineCacheAdapter)
16
Writing lock file
17
Generating autoload files

Afterwards, I also installed the two libraries it suggests, but did not install all of the next level of suggestions for my local development machine:

1
$ composer require aws/aws-php-sns-message-validator
2
Using version ^1.1 for aws/aws-php-sns-message-validator
3
./composer.json has been updated
4
Loading composer repositories with package information
5
Updating dependencies (including require-dev)
6
  - Installing aws/aws-php-sns-message-validator (1.1.0)   
7
    Loading from cache
8
9
Writing lock file
10
Generating autoload files
11
12
$ composer require cache/doctrine-adapter
13
Using version ^0.5.0 for cache/doctrine-adapter
14
./composer.json has been updated
15
Loading composer repositories with package information
16
Updating dependencies (including require-dev)
17
  - Installing doctrine/cache (v1.6.0)                     
18
    Loading from cache
19
20
  - Installing psr/cache (1.0.0)
21
    Loading from cache
22
23
  - Installing cache/taggable-cache (0.4.0)
24
    Loading from cache
25
26
  - Installing psr/log (1.0.0)
27
    Loading from cache
28
29
  - Installing cache/adapter-common (0.3.2)
30
    Loading from cache
31
32
  - Installing cache/doctrine-adapter (0.5.0)
33
    Loading from cache
34
35
cache/doctrine-adapter suggests installing ext-apc (Allows for caching with Apc)
36
cache/doctrine-adapter suggests installing ext-memcache (Allows for caching with Memcache)
37
cache/doctrine-adapter suggests installing ext-memcached (Allows for caching with Memcached)
38
cache/doctrine-adapter suggests installing ext-redis (Allows for caching with Redis)
39
Writing lock file
40
Generating autoload files

I also registered the awssdk component within hello/config/web.php:

1
'components' => [
2
      'awssdk' => [
3
        'class' => 'fedemotta\awssdk\AwsSdk',
4
        'credentials' => [
5
          //you can use a different method to grant access

6
          'key' => $config['aws_s3_access'],
7
          'secret' => $config['aws_s3_secret'],
8
        ],
9
        'region' => $config['aws_s3_region'], //i.e.: 'us-east-1'

10
        'version' => 'latest', //i.e.: 'latest'

11
      ],
12
    

Browsing My S3 Directories

For today's demonstration, I created a hello/controllers/StorageController.php with action methods to run each example, such as http://localhost:8888/hello/storage/browse to browse directories. 

These methods in turn call the Storage.php model I created with their own methods.

Here's the controller code:

1
public function actionBrowse()
2
    {
3
      $s = new Storage();
4
      $s->browse('jeff-reifman-wp',"manual");
5
    }

It requests that the Storage model reach up to the clouds in the "S3ky" and browse the manual directory.

Each time the Storage.php model is instantiated, it loads the AWS SDK extension and creates an S3 instance:

1
<?php
2
namespace app\models;
3
use Yii;
4
use yii\base\Model;
5
6
class Storage extends Model
7
{
8
9
  private $aws;
10
  private $s3;
11
12
   function __construct() {
13
     $this->aws = Yii::$app->awssdk->getAwsSdk();
14
     $this->s3 = $this->aws->createS3();
15
  }

In my browse example, I'm just echoing the directories and files, but you can feel free to customize this code as you need:

1
public function browse($bucket='',$prefix='') {
2
    $result = $this->s3->listObjects(['Bucket' => $bucket,"Prefix" => $prefix])->toArray();
3
    foreach ($result as $r) {
4
      if (is_array($r)) {
5
        if (array_key_exists('statusCode',$r)) {
6
            echo 'Effective URL: '.$r['effectiveUri'].'<br />';
7
        } else {
8
          foreach ($r as $item) {
9
            echo $item['Key'].'<br />';
10
          }
11
        }
12
      } else {
13
          echo $r.'<br />';
14
        }
15
    }
16
  }

Here are the results when I browse to http://localhost:8888/hello/storage/browse:

Yii AWS S3 - Browse S3 Objects a listing of directories and files Yii AWS S3 - Browse S3 Objects a listing of directories and files Yii AWS S3 - Browse S3 Objects a listing of directories and files

Uploading Files

To upload a file, you need to specify the local path and the remote destination key. Here's the controller code for upload:

1
public function actionUpload() {
2
    $bucket = 'jeff-reifman-wp';
3
    $keyname = '/manual/upload.txt';
4
    $filepath ='/Users/Jeff/Sites/hello/upload.txt';
5
    $s = new Storage();
6
    $result = $s->upload($bucket,$keyname,$filepath);
7
    echo $result['ObjectURL'];
8
  }

And here is the Storage model method:

1
public function upload($bucket,$keyname,$filepath) {
2
    $result = $this->s3->putObject(array(
3
    'Bucket'       => $bucket,
4
    'Key'          => $keyname,
5
    'SourceFile'   => $filepath,
6
    'ContentType'  => 'text/plain',
7
    'ACL'          => 'public-read',
8
    'StorageClass' => 'REDUCED_REDUNDANCY',
9
    'Metadata'     => array(
10
        'param1' => 'value 1',
11
        'param2' => 'value 2'
12
    )
13
));
14
return $result;

Browsing to http://localhost:8888/hello/storage/upload displays the returning URL from which I can view the uploaded file, because I specified public-read in my code above:

Yii AWS S3 - Results of Upload method - a URL to the new fileYii AWS S3 - Results of Upload method - a URL to the new fileYii AWS S3 - Results of Upload method - a URL to the new file

In turn, browsing to the S3 address above shows the contents of the uploaded file:

1
This is a test to upload to S3

Downloading Files

Here's the controller code for downloading a file:

1
public function actionDownload() {
2
    $s = new Storage();
3
    $f = $s->download('jeff-reifman-wp','files/2013/01/i103-wedding-cover.jpg');
4
    //download the file

5
    header('Content-Type: ' . $f['ContentType']);
6
    echo $f['Body'];
7
  }

Since the browser responds to the content-type, it should display the appropriate image, which I'm requesting here.

Note: I'm downloading a cover image from my experience marrying a corporation named Corporate Person to a woman (yes, it actually happened). The marriage didn't work out long term.

Here's the Storage model code for downloading:

1
public function download($bucket='',$key ='') {
2
    //get the last object from s3

3
    //$object = end($result['Contents']);

4
    // $key = $object['Key'];

5
    $file = $this->s3->getObject([
6
        'Bucket' => $bucket,
7
        'Key' => $key,
8
    ]);
9
    return $file;
10
    // save it to disk

11
  }

Here's what you see when the file is streamed to the browser—that's the bride celebrating by waving the actual marriage license to Corporate Person (I'm smiling in the background, mission accomplished).

Yii AWS S3 - Marriage Scene with Woman and Marriage LicenseYii AWS S3 - Marriage Scene with Woman and Marriage LicenseYii AWS S3 - Marriage Scene with Woman and Marriage License

Certainly, you could just as easily store the results on your server in a file. It's up to you. I encourage you to play with the code and customize it as you need.

What's Next?

I hope this helps you with the basics of using AWS S3 from your Yii application. 

If you like the concept of cloud-based object and file storage but want to find other providers, check out Alternatives to Amazon AWS. I've been gradually moving away from AWS for a number of reasons mentioned in the article. One of my next tasks is to migrate my S3 objects that are still partly in use to my own server, which I can mirror with KeyCDN.

Watch for upcoming tutorials in our Programming With Yii2 series as we continue diving into different aspects of the framework. You may also want to check out our Building Your Startup With PHP series which is using Yii2's advanced template as we build a real-world application. The Meeting Planner application in the startup series is now ready for use, and it's all built in Yii.

If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page

Related Links

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.