How to use amazon s3 using php

amazons3Amazon Simple Storage Service is designed to make web-scale computing easier for developers. If you have a medium to high traffic web application then S3 will help you to load your content faster. Here contents may be files, photos, videos or even text. Normally S3 is used for files, photos and videos. It gives any developer access to the same highly scalable, reliable, fast, inexpensive data storage infrastructure that Amazon uses to run its own global network of web sites.

3 months ago I developed a project for one of my client using Zend Framework. 1 week ago he told me to change the photo uploading system from hosting disk to amazon s3. Yesterday I implemented s3 for him and found its really very easy using Zend framework.

Here I’m describing how did I do so:

If you want to access S3 you’ve to signup in amazon s3 and need to get access key and secret key.

Here is a simple example of the basic usage using php and zend framework:

$secret   = "XXXXXXXXXXXXXXX";
$access  = "YYYYYYYYYYYYYYY";
$bucket  = "photo";

require_once 'Zend/Service/Amazon/S3.php';
$s3 = new Zend_Service_Amazon_S3($secret, $access);

$s3->createBucket("$bucket");
$s3->putObject("$bucket/myobject", "somedata");
echo $s3->getObject("$bucket/myobject");

At first you’ve to create a object $s3 of Zend_Service_Amazon_S3 class by providing your access and secret keys. Then you have to create a bucket. You can think bucket as folder where you’ll put your data.

Now I’m showing you another example little modified from my project. In my project I’ve a form from where user could upload photos from their computer.

<form name="fphoto" action="<?=BASE_URL?>/photos/photoupload" method="POST" enctype="multipart/form-data">
                    <input type="file" name="photo" size="80" /> <br />
                    <input type="submit" value="Submit" name="submit" />
                </form>

Where BASE_URL is the web application url and photos is the controller name and photoupload is the action name of photos controller. Now I used the following code to upload files in s3.

class PhotosController extends Zend_Controller_Action{
    function photouploadAction(){
        $access         =   "xxxxxxxxxxxxxxxxx";
        $secret          =   "yyyyyyyyyyyyyyy";
        $bucket         =   "user-photos";
        try{
            $s3         =   new Zend_Service_Amazon_S3($access, $secret);
            if (!$s3->isBucketAvailable($bucket))
                $s3->createBucket($bucket);

        }catch(Exception $o){
            print_r($o);
        }
        if ($_FILES['photo']['error'] == UPLOAD_ERR_OK && !empty($_FILES['photo']['tmp_name'])) {
            //file photo
            $sourceFile     =   $_FILES['photo']['tmp_name'];
            $type           =   $_FILES['photo']['type'];
            $name           =   $_FILES['photo']['name'];
            $size           =   $_FILES['photo']['size'];

            if ( preg_match("!(?:jpeg|png|gif|bmp)!i", $type) ){
                //upload photo to director. now amazon s3

                $lastId     =   1; //it is dynamically generated in my project using mysql
                $newFilename=   $lastId . strstr($name, '.');

                try{
                     $s3->putObject("$bucket/$newFilename", file_get_contents($sourceFile),
                        array(Zend_Service_Amazon_S3::S3_ACL_HEADER => Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ));
                }
                catch(Exception $o){
                    print_r($o);
                }
                $filepath     =   "http://s3.amazonaws.com/$bucket/$newFilename";
                //$filepath is the final path. I store it in my database for future reference

            }
        }
    }
}

Look I used file_get_contents() to read the source file. You can also provide url like http://somesite.com/image.jpg to this method to read the contents of that data. And then I store it in my bucket using $s3->putObject() method. When I put object in s3 I give public read permission so you can now see the image or file by just visiting http://s3.amazonaws.com/$bucket/$newFilename url. Where $newFilename will replaced by actual name.

I mention the codes here with little modification, actually I omit the database functionality here. But in my project I dynamically generate $lastId using mysql and store them and load them dynamically from S3. My intention was to show you how easy to use S3 service using php and zend framework.

About mahmud ahsan

Founder And Lead Programmer at iThinkdiff.net

, , ,

9 Responses to How to use amazon s3 using php

  1. eCommerce Plugin June 8, 2010 at 4:34 pm #

    You got a actually helpful blog I’ve been right here reading for about an hour. I’m a newbie and your achievement is incredibly a lot an inspiration for me.

  2. red shoes for men June 19, 2010 at 10:02 am #

    Great site! I抦 good sites fan keep up the good work!

  3. Roberto Hengl October 29, 2010 at 8:47 am #

    Hey useful post. I had a little difficulity viewing this article onOpera though, not sure why?

  4. Kyathi March 22, 2011 at 5:32 pm #

    Great Post… Thanks.

    Seems broken for me :-(

  5. vishnu April 12, 2011 at 9:47 am #

    Great post ..thank u

  6. agung susanto July 4, 2012 at 1:35 pm #

    Nice, Thanks….

  7. Fackelman September 16, 2013 at 5:19 pm #

    Great job – thanks for telling us how to do it.

  8. Lanphung October 10, 2013 at 3:36 pm #

    How to di this with code php basic ?

  9. Rainwalker February 10, 2014 at 3:46 pm #

    I never found a updated Script with Amazons latest sdk. i have made it by myself. it woks as a php commandline interpreter script. give it a try :

    https://github.com/arizawan/aiss3clientphp