;
 

AWS S3 with PHP on Apache

Posted by Ian on 4th Mar 2015

I'm been starting to use Amazon S3 for storing some files that are created and uploaded by my PHP application on an Apache web server. The AWS SDK for PHP is very good, fast and seems easy enough to use.

I had some problems with the "credentials". Firstly, even though PHP runs under my user account, it could not access the ~/.aws/credentials file in my users home, due to PHP security measures. Also, when I provided the credentials as options when instantiating the S3Client, the service would not connect, giving me the same error:

error retrieving credentials from the instance profile metadata server. when you are not running inside of amazon ec2, you must provide your aws access key id and secret access key in the ...

It turned out that the only way I could get the credentials to work was to create a credentials object separately and use that. E.g.

# Include the SDK using the Composer autoloader
require realpath(dirname(__FILE__)) . '/vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Common\Credentials\Credentials;

...

        # Note. other methods of providing the credentials did not work, so stick to this
        $credentials = new Credentials(S3_KEY, S3_SECRET);

        # Instantiate the S3 client with your AWS credentials
        $this->s3client = S3Client::factory(array(
            'credentials' => $credentials
        ));

That worked. Uploading files seems fast especially compared with rackspace.