PHP

Uploading files to Amazon S3 with REST API in PHP

CK CK 3788 
Created at
Updated at  
842 0 0

You can upload files with socket based REST API in PHP. In order to access Amazon S3 API, you need Access Key and Secret Key. Following is the example. 
 

<?php 
$aws_key = '_YOUR_AWS_KEY_000000'; 
$aws_secret = '_your_aws_secret_00000000000000000000000';$source_file = 'logo.gif'; // file to upload to S3 

$file_type = "image/gif";  // or other file type like "image/jpeg" for JPEG image, 
// or "binary/octet-stream" for binary file 

$aws_bucket = 'anyexample-test'; // AWS bucket 
$aws_object = 'logo.gif';         // AWS object name (file name) 

if (strlen($aws_secret) != 40) die("$aws_secret should be exactly 40 bytes long"); 
$file_data = file_get_contents($source_file); 
if ($file_data == false) die("Failed to read file ".$source_file); 

// opening HTTP connection to Amazon S3 
$fp = fsockopen("s3.amazonaws.com", 80, $errno, $errstr, 30); 
if (!$fp) { 
die("$errstr ($errno) "); 
} 

// Creating or updating bucket 

$dt = gmdate('r'); // GMT based timestamp// preparing String to Sign    (see AWS S3 Developer Guide) 

$string2sign = "PUT{$dt} 
/{$aws_bucket}" 

; 

// preparing HTTP PUT query 
$query = "PUT /{$aws_bucket} HTTP/1.1 
Host: s3.amazonaws.com 
Connection: keep-alive 
Date: $dt 
Authorization: AWS {$aws_key}:".amazon_hmac($string2sign)." "; 

$resp = sendREST($fp, $query); 
if (strpos($resp, '<Error>') !== false) 
die($resp);echo 

"BUCKET created "; 
// done// Uploading object 

$file_length = strlen($file_data); // for Content-Length HTTP field 

$dt = gmdate('r'); // GMT based timestamp 
// preparing String to Sign    (see AWS S3 Developer Guide) 
$string2sign = "PUT{$file_type} 
{$dt} 
x-amz-acl:public-read 
/{$aws_bucket}/{$aws_object}" 

; 

// preparing HTTP PUT query 
$query = "PUT /{$aws_bucket}/{$aws_object} HTTP/1.1 
Host: s3.amazonaws.com 
x-amz-acl: public-read 
Connection: keep-alive 
Content-Type: {$file_type} 
Content-Length: {$file_length} 
Date: $dt 
Authorization: AWS {$aws_key}:".amazon_hmac($string2sign)." "; 
$query .= $file_data; 

$resp = sendREST($fp, $query); 
if (strpos($resp, '<Error>') !== false) 
die($resp);echo 

"FILE uploaded "; 
// done 

echo "Your file's URL is:  http://s3.amazonaws.com/{$aws_bucket}/{$aws_object} "; 

fclose($fp); 

// Sending HTTP query and receiving, with trivial keep-alive support 
function sendREST($fp, $q, $debug = false) 
{ 
if ($debug) echo " QUERY<<{$q}>> "; 

fwrite($fp, $q); 
$r = ''; 
$check_header = true; 
while (!feof($fp)) { 
$tr = fgets($fp, 256); 
if ($debug) echo " RESPONSE<<{$tr}>>"; 
$r .= $tr;if (( 

$check_header)&&(strpos($r, " ") !== false)) 
{ 
// if content-length == 0, return query result 
if (strpos($r, 'Content-Length: 0') !== false) 
return $r; 
} 

// Keep-alive responses does not return EOF 
// they end with 0 string 
if (substr($r, -7) == " 0 ") 
return $r; 
} 
return $r; 
} 

// hmac-sha1 code START 
// hmac-sha1 function:  assuming key is global $aws_secret 40 bytes long 
// read more at http://en.wikipedia.org/wiki/HMAC 
// warning: key($aws_secret) is padded to 64 bytes with 0x0 after first function call 
function amazon_hmac($stringToSign) 
{ 
// helper function binsha1 for amazon_hmac (returns binary value of sha1 hash) 
if (!function_exists('binsha1')) 
{ 
if (version_compare(phpversion(), "5.0.0", ">=")) { 
function binsha1($d) { return sha1($d, true); } 
} else { 
function binsha1($d) { return pack('H*', sha1($d)); } 
} 
}global 

$aws_secret;if ( 

strlen($aws_secret) == 40) 
$aws_secret = $aws_secret.str_repeat(chr(0), 24); 

$ipad = str_repeat(chr(0x36), 64); 
$opad = str_repeat(chr(0x5c), 64); 

$hmac = binsha1(($aws_secret^$opad).binsha1(($aws_secret^$ipad).$stringToSign)); 
return base64_encode($hmac); 
} 
// hmac-sha1 code END 

 

Tags Amazon S3 Cloud Berry PHP REST S3 S3 Explorer Facebook X
Comments 0
Similar posts
  1. Where to get AWS Access Key ?
    11,262
  2. Amazon S3 File Explorer : You can use S3 like Windows File Explorer
    557
  3. Human readable random string for captchas in PHP
    559
  4. How to get the duration between days in PHP
    423
  5. How to create private URL on S3/CloudFront with time-limit ?
    919
  6. Function can extract file name in string having full path in PHP
    567
  7. Date format validation in PHP
    571
  8. PHP function converts new line to BR tag
    560
  9. Email Validation Snipet in PHP
    379
  10. PHP socket programming to get content with post method
    410
  11. Get Remote IP Address in PHP
    498
  12. How to remove HTML tags in text string?
    405
  13. Directory listing in PHP
    512
  14. Seconds to String in PHP
    436
  15. Apache server unstable detection and the related server(mysql, apache) restart automatically
    536
  16. Image file resizing in PHP
    561
  17. File downloading function through PHP code
    532
  18. mysql optimization – if you are using Word Press, do not turn off persistent connection
    592
  19. The public could reduce server cost, and enhance performance for global service distribution
    10,741
  20. JSON format control in PHP
    692
  21. How to delete file on certain path ?
    389
  22. GD library version in PHP
    505
  23. ASCII Artwork Generator from image file
    469
  24. Convert plain HTML to XHTML
    452
  25. How to limit by Timeout when opening URL ?
    458
  26. How to put timeout when opening URL by fopen ?
    441
  27. How to convert W3C Date Time Format ?
    456
  28. Get the actual filesize for a size above 2GB in Windows
    428
  29. HTML redirection in PHP
    399
  30. ISO 8601 format time format string conversion
    538
  1. Checking similarity between two strings in PHP
    674
  2. Simple PHP calendar
    474
  3. Simple PHP code performance measuring example
    792
  4. Convert plain HTML to XHTML
    452
  5. GD library version in PHP
    505
  6. JSON format control in PHP
    692
  7. mysql optimization – if you are using Word Press, do not turn off persistent connection
    592
  8. File downloading function through PHP code
    532
  9. Image file resizing in PHP
    561
  10. Apache server unstable detection and the related server(mysql, apache) restart automatically
    536
  11. How to set AUTO_INCREMENT ID in mySQL ?
    606
  12. Function can extract file name in string having full path in PHP
    567
  13. How to create private URL on S3/CloudFront with time-limit ?
    919
  14. Parsing XML in PHP
    1,192
  15. Unzip a ZIP file in PHP
    503
  16. Human readable random string for captchas in PHP
    559
  17. How to get browser information in PHP?
    852
  18. How to get the duration between days in PHP
    423
  19. Date format validation in PHP
    571
  20. PHP function converts new line to BR tag
    560
  21. Email Validation Snipet in PHP
    379
  22. PHP socket programming to get content with post method
    410
  23. Get Remote IP Address in PHP
    498
  24. How to remove HTML tags in text string?
    405
  25. Directory listing in PHP
    512
  26. Seconds to String in PHP
    436
  27. How to delete file on certain path ?
    389
  28. ASCII Artwork Generator from image file
    469
  29. How to limit by Timeout when opening URL ?
    458
  30. How to put timeout when opening URL by fopen ?
    441
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260