Uploading files to S3 Using PHP

Learn how to upload images to Amazon S3 using PHP with this step-by-step guide. S3 provides a scalable and reliable storage solution for your files(image/video/etc).

To upload files to S3 using PHP, you can use the AWS SDK for PHP or PHP's built-in curl functions. Here's an example using the AWS SDK for PHP:

 use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// Instantiate an S3 client
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'your-aws-region',
    'credentials' => [
        'key'    => 'your-aws-access-key-id',
        'secret' => 'your-aws-secret-access-key',
    ],
]);

// Set the bucket name and file path
$bucket = 'your-s3-bucket-name';
$key = 'path/to/your/file.txt';

// Upload a file to S3
try {
    $s3->putObject([
        'Bucket' => $bucket,
        'Key'    => $key,
        'Body'   => fopen('/path/to/your/local/file.txt', 'r'),
        'ACL'    => 'public-read', // or 'private'
    ]);
} catch (S3Exception $e) {
    echo "Error uploading file: " . $e->getMessage();
}

here is an example PHP curl code that demonstrates how to upload files (including images) to Amazon S3:

 <?php

// AWS S3 configuration
$bucket = 'your-bucket-name';
$key = 'your-AWS-access-key-id';
$secret = 'your-AWS-secret-access-key';
$region = 'your-AWS-region';
$endpoint = 'https://s3.'.$region.'.amazonaws.com';

// file to upload
$filepath = 'path/to/file.jpg';
$filename = 'file.jpg';
$filetype = mime_content_type($filepath);

// generate signature
$date = gmdate('Ymd\THis\Z');
$method = 'PUT';
$canonical_uri = '/'.$bucket.'/'.$filename;
$canonical_querystring = '';
$canonical_headers = "content-type:".$filetype."\n".'host:'.$bucket.'.'.$endpoint."\n".'x-amz-date:'.$date."\n";
$signed_headers = 'content-type;host;x-amz-date';
$payload_hash = hash_file('sha256', $filepath);
$canonical_request = $method."\n".$canonical_uri."\n".$canonical_querystring."\n".$canonical_headers."\n".$signed_headers."\n".$payload_hash;
$algorithm = 'AWS4-HMAC-SHA256';
$credential_scope = gmdate('Ymd')."/".$region."/s3/aws4_request";
$string_to_sign = $algorithm."\n".$date."\n".$credential_scope."\n".hash('sha256', $canonical_request);
$kSecret = 'AWS4'.$secret;
$kDate = hash_hmac('sha256', gmdate('Ymd'), $kSecret, true);
$kRegion = hash_hmac('sha256', $region, $kDate, true);
$kService = hash_hmac('sha256', 's3', $kRegion, true);
$kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
$signature = hash_hmac('sha256', $string_to_sign, $kSigning);

// create curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint.$canonical_uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filepath));
$headers = array(
    'Content-Type: '.$filetype,
    'Content-Length: '.filesize($filepath),
    'Authorization: '.$algorithm.' Credential='.$key.'/'.$credential_scope.', SignedHeaders='.$signed_headers.', Signature='.$signature,
    'Host: '.$bucket.'.'.$endpoint,
    'X-Amz-Date: '.$date
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// execute curl request
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error: '.curl_error($ch);
}
curl_close($ch);

echo 'File uploaded successfully.';

In this example, we use PHP curl to upload a file to Amazon S3. We start by defining the AWS S3 configuration variables (bucket name, access key, secret key, and region) and the file to upload (filepath, filename, and filetype).

Next, we generate a signature for the request using the AWS Signature Version 4 algorithm. This involves creating a canonical request and then signing it using a series of secret keys.

Finally, we create a curl request with the necessary headers (including the signature) and execute it to upload the file to S3.

Note that you will need to have the AWS SDK for PHP installed in order to use the S3Client method shown in the previous answer, whereas this solution uses just PHP curl.