How to upload file into s3 from ec2 using php?

by raven_corwin , in category: PHP General , 8 months ago

How to upload file into s3 from ec2 using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 8 months ago

@raven_corwin 

To upload a file into Amazon S3 from an EC2 instance using PHP, you can use the AWS SDK for PHP. Here's a step-by-step guide on how to upload a file to S3 from an EC2 instance:

  1. Install the AWS SDK for PHP: You can install the SDK using Composer by adding the following to your composer.json file:
1
2
3
4
5
{
    "require": {
        "aws/aws-sdk-php": "^3.0"
    }
}


Then, run composer install to install the SDK.

  1. Include the SDK in your PHP file:
1
2
3
require 'vendor/autoload.php';
use AwsS3S3Client;
use AwsCredentialsCredentialProvider;


  1. Set up your AWS credentials: Create a credentials file in the ~/.aws/ directory on your EC2 instance with your AWS access key and secret key:
1
2
3
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY


  1. Write the code to upload the file to S3:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
$bucket = 'your-bucket-name';
$key = 'path/to/uploaded/file.txt';
$filename = 'path/to/local/file.txt';

$client = new S3Client([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => 'latest'
]);

$result = $client->putObject([
    'Bucket' => $bucket,
    'Key' => $key,
    'Body' => fopen($filename, 'r'),
    'ACL' => 'public-read'
]);

echo 'File uploaded successfully';


Replace 'your-bucket-name', 'path/to/uploaded/file.txt', and 'path/to/local/file.txt' with your own values.

  1. Save the PHP file and run it on your EC2 instance. The file should be uploaded to the specified S3 bucket.


That's it! This is how you can upload a file to Amazon S3 from an EC2 instance using PHP.