S3 Upload: the simplest possible in PHP

amazon_s3

Most applications still aren’t uploading its files to S3, and this post is part of a series that tries to show the easiest possible way to implement this in different languages and technologies. Here we’ll show the simplest way in Php. For TL;DR version, just fork the repo and try it locally.

In order to use this implementation, we need to get the Amazon Php SDK, and you can get it easily via Composer (Don’t know what’s Composer? Stop everything you’re doing and read this site), creating composer.json file in the project root folder with the following content:

{
    "require": {
            "aws/aws-sdk-php": "2.*"
     }
}

After creating and modifying the config file, we need to download the dependencies, with this command:

php composer.phar install

Note that a vendor folder was created with AWS packages (in AWS SDK there are some extra libs accompanying Guzzle and Symfony Event Dispatcher).

Done with the dependencies, now it’s too easy. We have a very simple HTML form in the project with multipart/form-data encoding (index.php file), which submits to another file (upload.php) that receives form data and sends it straight to S3, without touching the local file system. We are using an existing bucket, but we could’ve also created a new bucket through the API.

Thus, we begin creating file index.php with the HTML form:

index.php

 



Example Upload to S3 in PHP




Upload file to S3

Then it’s time to create upload.php, which will handle the POST with data and store it in S3. Note that you’ll have to use your AWS account’s ACCESS_KEY and SECRET_KEY.

upload.php

<?
    define(ACCESS_KEY, "");
    define(SECRET_KEY, "");

    session_start();
    require "vendor/autoload.php";

    use Aws\S3\S3Client;

    try {       

        // fires an exception if there is no data sent
        if (!isset($_FILES['file'])) {
            throw new Exception("File not uploaded", 1);
        }

        // creates a client object, informing AWS credentials
        $clientS3 = S3Client::factory(array(
            'key'    => ACCESS_KEY,
            'secret' => SECRET_KEY
        ));

        // putObject method sends data to the chosen bucket (in our case, teste-marcelo)
        $response = $clientS3->putObject(array(
            'Bucket' => "teste-marcelo",
            'Key'    => $_FILES['file']['name'],
            'SourceFile' => $_FILES['file']['tmp_name'],
        ));

        $_SESSION['msg'] = "Object successfully posted, address <a href='{$response['ObjectURL']}'>{$response['ObjectURL']}</a>";

        header("location: index.php");

    } catch(Exception $e) {
        echo "Error > {$e->getMessage()}";
    }
?>

At the end of the upload, we get the new file’s URL from HTTP Response and send it to users. That’s it! Your files and now being sent to S3 in a very simple and efficient manner!

The source code is available in my github.

Gostou do conteúdo? Tem alguma dúvida? Entre em contato com nossos Especialistas Mandic Cloud, ficamos felizes em ajudá-lo.