PHP

Uploading files to Amazon S3 with REST API in PHP

CK1820 
Created at Sep 27, 2010 03:50:38
Updated at Feb 23, 2024 03:59:49 
343   0   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 Share on Facebook Share on X

◀ PREVIOUS
Human readable random string for captchas in PHP
▶ NEXT
Unzip a ZIP file in PHP
  Comments 0
Login for comment
SIMILAR POSTS

Where to get AWS Access Key ? (updated at Dec 21, 2023)

Amazon S3 File Explorer : You can use S3 like Windows File Explorer (created at Oct 02, 2010)

Unzip a ZIP file in PHP (created at Oct 24, 2010)

Human readable random string for captchas in PHP (created at Jul 05, 2010)

How to get browser information in PHP? (created at Jun 22, 2010)

How to get the duration between days in PHP (created at Jun 15, 2010)

Parsing XML in PHP (created at Mar 06, 2011)

How to create private URL on S3/CloudFront with time-limit ? (updated at Dec 17, 2023)

Function can extract file name in string having full path in PHP (updated at Dec 17, 2023)

Date format validation in PHP (created at Nov 28, 2009)

PHP function converts new line to BR tag (created at Nov 27, 2009)

Email Validation Snipet in PHP (created at Nov 08, 2009)

PHP socket programming to get content with post method (created at Oct 19, 2009)

Get Remote IP Address in PHP (created at Aug 16, 2009)

How to remove HTML tags in text string? (created at Aug 05, 2009)

Directory listing in PHP (created at Jul 06, 2009)

Seconds to String in PHP (created at Jun 06, 2009)

Apache server unstable detection and the related server(mysql, apache) restart automatically (updated at Dec 17, 2023)

Image file resizing in PHP (updated at Dec 17, 2023)

File downloading function through PHP code (updated at Dec 17, 2023)

mysql optimization – if you are using Word Press, do not turn off persistent connection (created at Jun 12, 2012)

The public could reduce server cost, and enhance performance for global service distribution (created at Jun 17, 2012)

JSON format control in PHP (updated at Apr 24, 2024)

How to delete file on certain path ? (created at Oct 01, 2008)

GD library version in PHP (updated at Jan 15, 2024)

ASCII Artwork Generator from image file (created at Sep 22, 2008)

Convert plain HTML to XHTML (updated at Dec 19, 2023)

How to limit by Timeout when opening URL ? (created at Apr 14, 2008)

How to put timeout when opening URL by fopen ? (created at Mar 31, 2008)

How to convert W3C Date Time Format ? (created at Feb 27, 2008)

OTHER POSTS IN THE SAME CATEGORY

Checking similarity between two strings in PHP (updated at Apr 21, 2024)

Simple PHP calendar (created at Jun 02, 2013)

Simple PHP code performance measuring example (updated at Jan 15, 2024)

Convert plain HTML to XHTML (updated at Dec 19, 2023)

GD library version in PHP (updated at Jan 15, 2024)

JSON format control in PHP (updated at Apr 24, 2024)

mysql optimization – if you are using Word Press, do not turn off persistent connection (created at Jun 12, 2012)

File downloading function through PHP code (updated at Dec 17, 2023)

Image file resizing in PHP (updated at Dec 17, 2023)

Apache server unstable detection and the related server(mysql, apache) restart automatically (updated at Dec 17, 2023)

How to set AUTO_INCREMENT ID in mySQL ? (updated at Jan 15, 2024)

Function can extract file name in string having full path in PHP (updated at Dec 17, 2023)

How to create private URL on S3/CloudFront with time-limit ? (updated at Dec 17, 2023)

Parsing XML in PHP (created at Mar 06, 2011)

Unzip a ZIP file in PHP (created at Oct 24, 2010)

Human readable random string for captchas in PHP (created at Jul 05, 2010)

How to get browser information in PHP? (created at Jun 22, 2010)

How to get the duration between days in PHP (created at Jun 15, 2010)

Date format validation in PHP (created at Nov 28, 2009)

PHP function converts new line to BR tag (created at Nov 27, 2009)

Email Validation Snipet in PHP (created at Nov 08, 2009)

PHP socket programming to get content with post method (created at Oct 19, 2009)

Get Remote IP Address in PHP (created at Aug 16, 2009)

How to remove HTML tags in text string? (created at Aug 05, 2009)

Directory listing in PHP (created at Jul 06, 2009)

Seconds to String in PHP (created at Jun 06, 2009)

How to delete file on certain path ? (created at Oct 01, 2008)

ASCII Artwork Generator from image file (created at Sep 22, 2008)

How to limit by Timeout when opening URL ? (created at Apr 14, 2008)

How to put timeout when opening URL by fopen ? (created at Mar 31, 2008)

UPDATES

Creating a Pinterest-Style Card Layout with Bootstrap and Masonry (created at Apr 24, 2024)

Mastering Excel Data Importation in PHP (updated at Apr 24, 2024)

JSON format control in PHP (updated at Apr 24, 2024)

Equal Height Blocks in Bootstrap with JavaScript (created at Apr 22, 2024)

How to convert integer to text string ? (updated at Apr 22, 2024)

Checking similarity between two strings in PHP (updated at Apr 21, 2024)

Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file (updated at Apr 21, 2024)

How do I determine the client IP type (IPv4/IPv6) in PHP (updated at Apr 16, 2024)

How do I determine the client IP type in Python - IPv4 or IPv6 (updated at Apr 13, 2024)

Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network (updated at Apr 09, 2024)

Predicting Buyer Preferences with PyTorch: A Deep Learning Approach (updated at Apr 09, 2024)

Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction (created at Apr 09, 2024)

PyTorch example to Forcast Stock Price based on 10 days Dataset (created at Apr 09, 2024)

Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python (created at Apr 08, 2024)

Harnessing the Power of Random Forest Algorithm in Python (created at Apr 08, 2024)

Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python (created at Apr 08, 2024)

Forecasting with Linear Regression and KNN Regression in Python (updated at Apr 07, 2024)

What is 302 Found Redirection in HTTP 1.1? (created at Apr 04, 2024)

Mastering Random Forest Regression: A Comprehensive Guide with Python Examples (updated at Apr 01, 2024)

Python Implementation of Linear Regression (updated at Apr 01, 2024)

Mastering Supervised Machine Learning with Python: A Comprehensive Guide (created at Apr 01, 2024)

Mastering AI: A Beginner's Guide to Python Programming and Beyond (created at Apr 01, 2024)

How do I create animated background for Google Meet? (updated at Mar 28, 2024)

Building a Simple DNS Server in Delphi with TTL Support (created at Mar 16, 2024)

How to force cookies, disable php sessid in URL ? (updated at Mar 16, 2024)

Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records (updated at Mar 16, 2024)

Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records (created at Mar 16, 2024)

Building a Basic DNS Server in PHP/Python: A Beginner's Guide (updated at Mar 15, 2024)

Dynamic DNS Made Easy: Building a Python-Based Solution (created at Mar 15, 2024)

Exploring the Depths of Data Transfer: sendfile vs. kTLS (created at Mar 15, 2024)