Sure, to upload a file to an AWS S3 bucket using PHP, you can utilize the AWS SDK for PHP, specifically the AWS S3 client. Here’s an example of how you might accomplish this:
First, make sure you have the AWS SDK for PHP installed using Composer. Create a composer.json
file with the following content
{
"require": {
"aws/aws-sdk-php": "^3.0"
}
}
Then, run composer install
to install the AWS SDK for PHP.
Next, use the following PHP code to upload a file to an S3 bucket
<?php
require 'vendor/autoload.php'; // Include the Composer autoload file
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
// Replace these values with your AWS credentials and bucket information
$bucketName = 'your-bucket-name';
$accessKeyId = 'your-access-key-id';
$secretAccessKey = 'your-secret-access-key';
$region = 'your-aws-region'; // e.g., 'us-west-1'
// File to upload
$filePath = '/path/to/your/file.txt'; // Replace with the path to your file
$keyName = 'file.txt'; // The name you want to give to the file in the bucket
// Create an S3 client
$s3 = new S3Client([
'version' => 'latest',
'region' => $region,
'credentials' => [
'key' => $accessKeyId,
'secret' => $secretAccessKey,
]
]);
try {
// Upload a file to the S3 bucket
$result = $s3->putObject([
'Bucket' => $bucketName,
'Key' => $keyName,
'SourceFile' => $filePath,
'ACL' => 'public-read', // Set ACL permissions for the uploaded file
]);
// Print the URL of the uploaded file
echo "File uploaded successfully. URL: " . $result['ObjectURL'];
} catch (AwsException $e) {
// Display error messages, if any
echo $e->getMessage();
}
?>
Remember to replace 'your-bucket-name'
, 'your-access-key-id'
, 'your-secret-access-key'
, 'your-aws-region'
, '/path/to/your/file.txt'
, and 'file.txt'
with your actual AWS S3 bucket name, credentials, region, local file path, and desired file name/key for the S3 bucket.
This code initializes the S3 client, specifies the file to upload, and then uses the putObject
method to upload the file to the specified S3 bucket.
Additionally, ensure that your AWS credentials have the necessary permissions to upload files to the designated S3 bucket.