Amazon S3 file upload using PHP

amazon-s3-upload

Amazon S3 file upload using PHP, Amazon is one of the biggest company for selling cloud computing servers. They have services, Amazon s3 is also a big service for playing with storage. Here we will learn how to upload a file into Amazon S3 storage server using PHP SDK. Its very easy, if you follow the bellow code.



First create amazon s3 key and secret access

  1. Go to – https://aws.amazon.com/s3/
  2. Click the top right button ‘Sign in to the Console
  3. Now sign in using your email and password
  4. After sign in, you can see ‘AWS Management Console
  5. Find your services, enter ‘S3‘ there and click on ‘S3‘ from dropdown
  6. Now create your S3 Bucket
  7. After create your bucket, click on your name in top right side, a dropdown menu will be showed
  8. Click on ‘My Security Credentials‘ from that dropdown
  9. Now you are able to see some ‘Accordion’ Menu, may be 3rd one is ‘Access keys (access key ID and secret access key)
  10. Click there and create your access keys and secrets.

Then download Amazon S3 PHP SDK from here

Download the SDK files, put into the directory of your PHP files. Rename the folder name as ‘aws-module‘.

Create a PHP file and put the following configuration code

$s3config = array(
            'region'  => 'us-west-2',
            'version' => 'latest',
            'credentials' => [
                'key'    => '******************',//Put key here
                'secret' => '*******************'// Put Secret here
            ]
        );
$bucket = 'your bucket name here'; 

Add the following code to upload file

<form method='post'>
    <input type='file' name='file'>
    <input type='submit'>
</form>

if($_POST)
{
	require 'aws-module/aws-autoloader.php';
	$tmpfile = $_FILES['file'];
	$s3 = new Aws\S3\S3Client($s3config);
	$key = str_replace(".","-".rand(1,9999).".",$tmpfile['name']);
	$result = $s3->putObject([
		'Bucket' => $bucket,
		'Key'    => $key,
		'SourceFile' => $tmpfile['tmp_name'],
		'ACL'   => 'public-read'
	]);
	$file_url = $result['ObjectURL'];
        echo 'Upload Success';
        echo $file_url;
}

Leave a Comment