Title: PHP S3 upload progress
Tags: php;amazon-s3
Question: This has gone around a number of times but I'm still a bit bewildered. A lot of answers only copncern themselves with talking about upload progress bars and not getting the actual upload progress from an S3 upload.
I have read a number of questions and found a number of software pieces but I am still no closer to understanding the fundamental question of S3 uploads.
Is there a way of uploading to S3 while understanding the progress of that upload without having to use my own app servers resources to store the file in the temp directory first?
Do I have to store the file on my own server first and then push to S3? I have heard people talk about streaming bit at a time to S3 (one chunk at a time) but I am unsure what this involves. Imagine I was uploading from client side in a HTML page how would I stream the file chunk by chunk from a multi-part from as it comes in? (I don't see any example of that only an example of when the file is already on your system and you know the chunks which is kinda useless tbh).
There is of course an example of upload progress in the API docs but again that is assuming the file is on your server first and is not coming from another computer supplied by the user.
EDIT: My original thought was to make a PHP script that could ping AWS once every so oftern getting upload progress. I am looking through the API to see if they do support something like that but atm no luck. Let me know if there is something...
Further EDIT: Is flash the only way to go with this?
Thanks,

Here is the accepted answer: YES, it is possible in AWS PHP SDK v3.
$client = new S3Client(/* config */);
$result = $client-&gt;putObject([
'Bucket'     =&gt; 'bucket-name',
'Key'        =&gt; 'bucket-name/file.ext',
'SourceFile' =&gt; 'local-file.ext',
'ContentType' =&gt; 'application/pdf',
'params' =&gt; [
'@http' =&gt; [
'progress' =&gt; function ($downloadTotalSize, $downloadSizeSoFar, $uploadTotalSize, $uploadSizeSoFar) {
printf(
&quot;%s of %s downloaded, %s of %s uploaded.\n&quot;,
$downloadSizeSoFar,
$downloadTotalSize,
$uploadSizeSoFar,
$uploadTotalSize
);
}
]
This is explained in the AWS docs - S3 Config section. It works by exposing GuzzleHttp's progress property-callable, as explained in this SO answer.
Comment for this answer: If you want the print on the same line just change to `\r` instead of `\n`

Here is another answer: Yes,you can do this by modifying s3.php like this,
<?php
class S3Withprogressbar {
// ACL flags
const ACL_PRIVATE = 'private';
const ACL_PUBLIC_READ = 'public-read';
const ACL_PUBLIC_READ_WRITE = 'public-read-write';
private static $__accessKey; // AWS Access key
private static $__secretKey; // AWS Secret key
public static $_uploadProgressFileName="" ;//uploadProgressFileName
public function __construct($accessKey = null, $secretKey = null) {
if ($accessKey !== null &amp;&amp; $secretKey !== null)
sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0setAuth($accessKey, $secretKey);
public static function setAuth($accessKey, $secretKey) {
sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$__accessKey = $accessKey;
sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$__secretKey = $secretKey;
public static function listBuckets($detailed = false) {
$rest = new S3Request('GET', '', '');
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 200)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0listBuckets(): [%s] %s", $rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
$results = array(); //var_dump($rest-&gt;body);
if (!isset($rest-&gt;body-&gt;Buckets)) return $results;
if ($detailed) {
if (isset($rest-&gt;body-&gt;Owner, $rest-&gt;body-&gt;Owner-&gt;ID, $rest-&gt;body-&gt;Owner-&gt;DisplayName))
$results['owner'] = array(
'id' =&gt; (string)$rest-&gt;body-&gt;Owner-&gt;ID, 'name' =&gt; (string)$rest-&gt;body-&gt;Owner-&gt;ID
$results['buckets'] = array();
foreach ($rest-&gt;body-&gt;Buckets-&gt;Bucket as $b)
$results['buckets'][] = array(
'name' =&gt; (string)$b-&gt;Name, 'time' =&gt; strtotime((string)$b-&gt;CreationDate)
} else
foreach ($rest-&gt;body-&gt;Buckets-&gt;Bucket as $b) $results[] = (string)$b-&gt;Name;
return $results;
public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null) {
$rest = new S3Request('GET', $bucket, '');
if ($prefix !== null &amp;&amp; $prefix !== '') $rest-&gt;setParameter('prefix', $prefix);
if ($marker !== null &amp;&amp; $prefix !== '') $rest-&gt;setParameter('marker', $marker);
if ($maxKeys !== null &amp;&amp; $prefix !== '') $rest-&gt;setParameter('max-keys', $maxKeys);
$response = $rest-&gt;getResponse();
if ($response-&gt;error === false &amp;&amp; $response-&gt;code !== 200)
$response-&gt;error = array('code' =&gt; $response-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($response-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0getBucket(): [%s] %s", $response-&gt;error['code'], $response-&gt;error['message']), E_USER_WARNING);
return false;
$results = array();
$lastMarker = null;
if (isset($response-&gt;body, $response-&gt;body-&gt;Contents))
foreach ($response-&gt;body-&gt;Contents as $c) {
$results[(string)$c-&gt;Key] = array(
'name' =&gt; (string)$c-&gt;Key,
'time' =&gt; strToTime((string)$c-&gt;LastModified),
'size' =&gt; (int)$c-&gt;Size,
'hash' =&gt; substr((string)$c-&gt;ETag, 1, -1)
$lastMarker = (string)$c-&gt;Key;
//$response-&gt;body-&gt;IsTruncated = 'true'; break;
if (isset($response-&gt;body-&gt;IsTruncated) &amp;&amp;
(string)$response-&gt;body-&gt;IsTruncated == 'false') return $results;
// Loop through truncated results if maxKeys isn't specified
if ($maxKeys == null &amp;&amp; $lastMarker !== null &amp;&amp; (string)$response-&gt;body-&gt;IsTruncated == 'true')
$rest = new S3Request('GET', $bucket, '');
if ($prefix !== null) $rest-&gt;setParameter('prefix', $prefix);
$rest-&gt;setParameter('marker', $lastMarker);
if (($response = $rest-&gt;getResponse(true)) == false || $response-&gt;code !== 200) break;
if (isset($response-&gt;body, $response-&gt;body-&gt;Contents))
foreach ($response-&gt;body-&gt;Contents as $c) {
$results[(string)$c-&gt;Key] = array(
'name' =&gt; (string)$c-&gt;Key,
'time' =&gt; strToTime((string)$c-&gt;LastModified),
'size' =&gt; (int)$c-&gt;Size,
'hash' =&gt; substr((string)$c-&gt;ETag, 1, -1)
$lastMarker = (string)$c-&gt;Key;
} while ($response !== false &amp;&amp; (string)$response-&gt;body-&gt;IsTruncated == 'true');
return $results;
public function putBucket($bucket, $acl = sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0ACL_PRIVATE) {
$rest = new S3Request('PUT', $bucket, '');
$rest-&gt;setAmzHeader('x-amz-acl', $acl);
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 200)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
//trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0putBucket({$bucket}): [%s] %s", $rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
return true;
public function deleteBucket($bucket = '') {
$rest = new S3Request('DELETE', $bucket);
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 204)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0leteBucket({$bucket}): [%s] %s",
$rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
return true;
public static function inputFile($file, $md5sum = true) {
if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
trigger_error('S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
return false;
return array('file' =&gt; $file, 'size' =&gt; filesize($file),
'md5sum' =&gt; $md5sum !== false ? (is_string($md5sum) ? $md5sum :
base64_encode(md5_file($file, true))) : '');
public static function inputResource(&amp;$resource, $bufferSize, $md5sum = '') {
if (!is_resource($resource) || $bufferSize <= 0) {
trigger_error('S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0inputResource(): Invalid resource or buffer size', E_USER_WARNING);
return false;
$input = array('size' =&gt; $bufferSize, 'md5sum' =&gt; $md5sum);
$input['fp'] =&amp; $resource;
return $input;
// Modified Function with one more  parameter $uploadProgressFileName
public static function putObject($input, $bucket, $uri, $acl = sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0ACL_PRIVATE, $metaHeaders = array(), $contentType = null,$uploadProgressFileName) {
if ($input == false) return false;
$rest = new S3Request('PUT', $bucket, $uri);
// Set public variable value($uploadProgressFileName) in S3Request class
$rest-&gt;uploadProgressFileName = $uploadProgressFileName;
if (is_string($input)) $input = array(
'data' =&gt; $input, 'size' =&gt; strlen($input),
'md5sum' =&gt; base64_encode(md5($input, true))
// Data
if (isset($input['fp']))
$rest-&gt;fp =&amp; $input['fp'];
elseif (isset($input['file']))
$rest-&gt;fp = @fopen($input['file'], 'rb');
elseif (isset($input['data']))
$rest-&gt;data = $input['data'];
// Content-Length (required)
if (isset($input['size']) &amp;&amp; $input['size'] &gt; 0)
$rest-&gt;size = $input['size'];
else {
if (isset($input['file']))
$rest-&gt;size = filesize($input['file']);
elseif (isset($input['data']))
$rest-&gt;size = strlen($input['data']);
// Content-Type
if ($contentType !== null)
$input['type'] = $contentType;
elseif (!isset($input['type']) &amp;&amp; isset($input['file']))
$input['type'] = sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0__getMimeType($input['file']);
$input['type'] = 'application/octet-stream';
// We need to post with the content-length and content-type, MD5 is optional
if ($rest-&gt;size &gt; 0 &amp;&amp; ($rest-&gt;fp !== false || $rest-&gt;data !== false)) {
$rest-&gt;setHeader('Content-Type', $input['type']);
if (isset($input['md5sum'])) $rest-&gt;setHeader('Content-MD5', $input['md5sum']);
$rest-&gt;setAmzHeader('x-amz-acl', $acl);
foreach ($metaHeaders as $h =&gt; $v) $rest-&gt;setAmzHeader('x-amz-meta-'.$h, $v);
$rest-&gt;getResponse();
} else
$rest-&gt;response-&gt;error = array('code' =&gt; 0, 'message' =&gt; 'Missing input parameters');
if ($rest-&gt;response-&gt;error === false &amp;&amp; $rest-&gt;response-&gt;code !== 200)
$rest-&gt;response-&gt;error = array('code' =&gt; $rest-&gt;response-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;response-&gt;error !== false) {
//trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0putObject(): [%s] %s", $rest-&gt;response-&gt;error['code'], $rest-&gt;response-&gt;error['message']), E_USER_WARNING);
return false;
return true;
// Modified Function with one more  parameter $uploadProgressFileName
public static function putObjectFile($file, $bucket, $uri, $acl = sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0ACL_PRIVATE, $metaHeaders = array(), $contentType = null,$uploadProgressFileName) {
return sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0putObject(S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType,$uploadProgressFileName);
public function putObjectString($string, $bucket, $uri, $acl = sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
return sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
public static function getObject($bucket = '', $uri = '', $saveTo = false) {
$rest = new S3Request('GET', $bucket, $uri);
if ($saveTo !== false) {
if (is_resource($saveTo))
$rest-&gt;fp =&amp; $saveTo;
if (($rest-&gt;fp = @fopen($saveTo, 'wb')) == false)
$rest-&gt;response-&gt;error = array('code' =&gt; 0, 'message' =&gt; 'Unable to open save file for writing: '.$saveTo);
if ($rest-&gt;response-&gt;error === false) $rest-&gt;getResponse();
if ($rest-&gt;response-&gt;error === false &amp;&amp; $rest-&gt;response-&gt;code !== 200)
$rest-&gt;response-&gt;error = array('code' =&gt; $rest-&gt;response-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;response-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0getObject({$bucket}, {$uri}): [%s] %s",
$rest-&gt;response-&gt;error['code'], $rest-&gt;response-&gt;error['message']), E_USER_WARNING);
return false;
$rest-&gt;file = realpath($saveTo);
return $rest-&gt;response;
public static function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) {
$rest = new S3Request('HEAD', $bucket, $uri);
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; ($rest-&gt;code !== 200 &amp;&amp; $rest-&gt;code !== 404))
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0getObjectInfo({$bucket}, {$uri}): [%s] %s",
$rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
return $rest-&gt;code == 200 ? $returnInfo ? $rest-&gt;headers : true : false;
public static function setBucketLogging($bucket, $targetBucket, $targetPrefix) {
$dom = new DOMDocument;
$bucketLoggingStatus = $dom-&gt;createElement('BucketLoggingStatus');
$bucketLoggingStatus-&gt;setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
$loggingEnabled = $dom-&gt;createElement('LoggingEnabled');
$loggingEnabled-&gt;appendChild($dom-&gt;createElement('TargetBucket', $targetBucket));
$loggingEnabled-&gt;appendChild($dom-&gt;createElement('TargetPrefix', $targetPrefix));
// TODO: Add TargetGrants
$bucketLoggingStatus-&gt;appendChild($loggingEnabled);
$dom-&gt;appendChild($bucketLoggingStatus);
$rest = new S3Request('PUT', $bucket, '');
$rest-&gt;setParameter('logging', null);
$rest-&gt;data = $dom-&gt;saveXML();
$rest-&gt;size = strlen($rest-&gt;data);
$rest-&gt;setHeader('Content-Type', 'application/xml');
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 200)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0setBucketLogging({$bucket}, {$uri}): [%s] %s",
$rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
return true;
public static function getBucketLogging($bucket = '') {
$rest = new S3Request('GET', $bucket, '');
$rest-&gt;setParameter('logging', null);
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 200)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0getBucketLogging({$bucket}): [%s] %s",
$rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
if (!isset($rest-&gt;body-&gt;LoggingEnabled)) return false; // No logging
return array(
'targetBucket' =&gt; (string)$rest-&gt;body-&gt;LoggingEnabled-&gt;TargetBucket,
'targetPrefix' =&gt; (string)$rest-&gt;body-&gt;LoggingEnabled-&gt;TargetPrefix,
public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
$dom = new DOMDocument;
$dom-&gt;formatOutput = true;
$accessControlPolicy = $dom-&gt;createElement('AccessControlPolicy');
$accessControlList = $dom-&gt;createElement('AccessControlList');
// It seems the owner has to be passed along too
$owner = $dom-&gt;createElement('Owner');
$owner-&gt;appendChild($dom-&gt;createElement('ID', $acp['owner']['id']));
$owner-&gt;appendChild($dom-&gt;createElement('DisplayName', $acp['owner']['name']));
$accessControlPolicy-&gt;appendChild($owner);
foreach ($acp['acl'] as $g) {
$grant = $dom-&gt;createElement('Grant');
$grantee = $dom-&gt;createElement('Grantee');
$grantee-&gt;setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
$grantee-&gt;setAttribute('xsi:type', 'CanonicalUser');
$grantee-&gt;appendChild($dom-&gt;createElement('ID', $g['id']));
} elseif (isset($g['email'])) { // AmazonCustomerByEmail
$grantee-&gt;setAttribute('xsi:type', 'AmazonCustomerByEmail');
$grantee-&gt;appendChild($dom-&gt;createElement('EmailAddress', $g['email']));
} elseif ($g['type'] == 'Group') { // Group
$grantee-&gt;setAttribute('xsi:type', 'Group');
$grantee-&gt;appendChild($dom-&gt;createElement('URI', $g['uri']));
$grant-&gt;appendChild($grantee);
$grant-&gt;appendChild($dom-&gt;createElement('Permission', $g['permission']));
$accessControlList-&gt;appendChild($grant);
$accessControlPolicy-&gt;appendChild($accessControlList);
$dom-&gt;appendChild($accessControlPolicy);
$rest = new S3Request('PUT', $bucket, '');
$rest-&gt;setParameter('acl', null);
$rest-&gt;data = $dom-&gt;saveXML();
$rest-&gt;size = strlen($rest-&gt;data);
$rest-&gt;setHeader('Content-Type', 'application/xml');
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 200)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
return true;
public static function getAccessControlPolicy($bucket, $uri = '') {
$rest = new S3Request('GET', $bucket, $uri);
$rest-&gt;setParameter('acl', null);
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 200)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
$acp = array();
if (isset($rest-&gt;body-&gt;Owner, $rest-&gt;body-&gt;Owner-&gt;ID, $rest-&gt;body-&gt;Owner-&gt;DisplayName)) {
$acp['owner'] = array(
'id' =&gt; (string)$rest-&gt;body-&gt;Owner-&gt;ID, 'name' =&gt; (string)$rest-&gt;body-&gt;Owner-&gt;DisplayName
if (isset($rest-&gt;body-&gt;AccessControlList)) {
$acp['acl'] = array();
foreach ($rest-&gt;body-&gt;AccessControlList-&gt;Grant as $grant) {
foreach ($grant-&gt;Grantee as $grantee) {
if (isset($grantee-&gt;ID, $grantee-&gt;DisplayName)) // CanonicalUser
$acp['acl'][] = array(
'type' =&gt; 'CanonicalUser',
'id' =&gt; (string)$grantee-&gt;ID,
'name' =&gt; (string)$grantee-&gt;DisplayName,
'permission' =&gt; (string)$grant-&gt;Permission
elseif (isset($grantee-&gt;EmailAddress)) // AmazonCustomerByEmail
$acp['acl'][] = array(
'type' =&gt; 'AmazonCustomerByEmail',
'email' =&gt; (string)$grantee-&gt;EmailAddress,
'permission' =&gt; (string)$grant-&gt;Permission
elseif (isset($grantee-&gt;URI)) // Group
$acp['acl'][] = array(
'type' =&gt; 'Group',
'uri' =&gt; (string)$grantee-&gt;URI,
'permission' =&gt; (string)$grant-&gt;Permission
else continue;
return $acp;
public static function deleteObject($bucket = '', $uri = '') {
$rest = new S3Request('DELETE', $bucket, $uri);
$rest = $rest-&gt;getResponse();
if ($rest-&gt;error === false &amp;&amp; $rest-&gt;code !== 204)
$rest-&gt;error = array('code' =&gt; $rest-&gt;code, 'message' =&gt; 'Unexpected HTTP status');
if ($rest-&gt;error !== false) {
trigger_error(sprintf("S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0leteObject(): [%s] %s", $rest-&gt;error['code'], $rest-&gt;error['message']), E_USER_WARNING);
return false;
return true;
public static function __getMimeType(&amp;$file) {
$type = false;
// Fileinfo documentation says fileinfo_open() will use the
// MAGIC env var for the magic file
if (extension_loaded('fileinfo') &amp;&amp; isset($_ENV['MAGIC']) &amp;&amp;
($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
if (($type = finfo_file($finfo, $file)) !== false) {
// Remove the charset and grab the last content-type
$type = explode(' ', str_replace('; charset=', ';charset=', $type));
$type = array_pop($type);
$type = explode(';', $type);
$type = array_shift($type);
finfo_close($finfo);
// If anyone is still using mime_content_type()
} elseif (function_exists('mime_content_type'))
$type = mime_content_type($file);
if ($type !== false &amp;&amp; strlen($type) &gt; 0) return $type;
// Otherwise do it the old fashioned way
static $exts = array(
'jpg' =&gt; 'image/jpeg', 'gif' =&gt; 'image/gif', 'png' =&gt; 'image/png',
'tif' =&gt; 'image/tiff', 'tiff' =&gt; 'image/tiff', 'ico' =&gt; 'image/x-icon',
'swf' =&gt; 'application/x-shockwave-flash', 'pdf' =&gt; 'application/pdf',
'zip' =&gt; 'application/zip', 'gz' =&gt; 'application/x-gzip',
'tar' =&gt; 'application/x-tar', 'bz' =&gt; 'application/x-bzip',
'bz2' =&gt; 'application/x-bzip2', 'txt' =&gt; 'text/plain',
'asc' =&gt; 'text/plain', 'htm' =&gt; 'text/html', 'html' =&gt; 'text/html',
'xml' =&gt; 'text/xml', 'xsl' =&gt; 'application/xsl+xml',
'ogg' =&gt; 'application/ogg', 'mp3' =&gt; 'audio/mpeg', 'wav' =&gt; 'audio/x-wav',
'avi' =&gt; 'video/x-msvideo', 'mpg' =&gt; 'video/mpeg', 'mpeg' =&gt; 'video/mpeg',
'mov' =&gt; 'video/quicktime', 'flv' =&gt; 'video/x-flv', 'php' =&gt; 'text/x-php'
$ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
public static function __getSignature($string) {
return 'AWS '.sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$__accessKey.':'.base64_encode(extension_loaded('hash') ?
hash_hmac('sha1', $string, sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$__secretKey, true) : pack('H*', sha1(
(str_pad(sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
pack('H*', sha1((str_pad(sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$__secretKey, 64, chr(0x00)) ^
(str_repeat(chr(0x36), 64))) . $string)))));
final class S3Request {
private $verb, $bucket, $uri, $resource = '', $parameters = array(),
$amzHeaders = array(), $headers = array(
'Host' =&gt; '', 'Date' =&gt; '', 'Content-MD5' =&gt; '', 'Content-Type' =&gt; ''
public $fp = false, $size = 0, $data = false, $response;
public $uploadProgressFileName;
function __construct($verb, $bucket = '', $uri = '') {
$this-&gt;verb = $verb;
$this-&gt;bucket = strtolower($bucket);
$this-&gt;uri = $uri !== '' ? '/'.$uri : '/';
if ($this-&gt;bucket !== '') {
$this-&gt;bucket = explode('/', $this-&gt;bucket);
$this-&gt;resource = '/'.$this-&gt;bucket[0].$this-&gt;uri;
$this-&gt;headers['Host'] = $this-&gt;bucket[0].'.s3.amazonaws.com';
$this-&gt;bucket = implode('/', $this-&gt;bucket);
} else {
$this-&gt;headers['Host'] = 's3.amazonaws.com';
if (strlen($this-&gt;uri) &gt; 1)
$this-&gt;resource = '/'.$this-&gt;bucket.$this-&gt;uri;
else $this-&gt;resource = $this-&gt;uri;
$this-&gt;headers['Date'] = gmdate('D, d M Y H:i:s T');
$this-&gt;response = new STDClass;
$this-&gt;response-&gt;error = false;
$this-&gt;response-&gt;body  = false;
$CI =&amp; get_instance();
$CI-&gt;load-&gt;helper('file');
public function setParameter($key, $value) {
$this-&gt;parameters[$key] = $value;
public function setHeader($key, $value) {
$this-&gt;headers[$key] = $value;
public function setAmzHeader($key, $value) {
$this-&gt;amzHeaders[$key] = $value;
//:callback function for upload progress.
public function progressCallback_new_curl($new,$download_size, $downloaded_size, $upload_size, $uploaded_size )
ob_start();
static $previousProgress = 0;
if ( $upload_size == 0 )
$progress = 0;
$progress = round( $uploaded_size * 100 / $upload_size );
if ( $progress &gt; $previousProgress)
flush();
$previousProgress = $progress;
$new_file_path = FCPATH.'upload/'.$this-&gt;uploadProgressFileName.'.txt'; // modify this line to point to the actual location of the file
write_file($new_file_path, $progress."\n");
// Check for Cancel upload text file and if exists return 1 to interrupt curl upload process.
$cancel_path=FCPATH.'upload/cancel_'.$this-&gt;uploadProgressFileName.'.txt';
if(file_exists($cancel_path)){
unlink($cancel_path);
if(file_exists($new_file_path)){
unlink($new_file_path);
return 1;
}
ob_flush();
flush();
public function progressCallback_old_curl($download_size, $downloaded_size, $upload_size, $uploaded_size )
ob_start();
static $previousProgress = 0;
if ( $upload_size == 0 )
$progress = 0;
$progress = round( $uploaded_size * 100 / $upload_size );
if ( $progress &gt; $previousProgress)
flush();
$previousProgress = $progress;
$new_file_path = FCPATH.'upload/'.$this-&gt;uploadProgressFileName.'.txt'; // modify this line to point to the actual location of the file
write_file($new_file_path, $progress."\n");
// Check for Cancel upload text file and if exists return 1 to interrupt curl upload process.
$cancel_path=FCPATH.'upload/cancel_'.$this-&gt;uploadProgressFileName.'.txt';
if(file_exists($cancel_path)){
unlink($cancel_path);
if(file_exists($new_file_path)){
unlink($new_file_path);
return 1;
ob_flush();
flush();
public function getResponse() {
$query = '';
if (sizeof($this-&gt;parameters) &gt; 0) {
$query = substr($this-&gt;uri, -1) !== '?' ? '?' : '&amp;';
foreach ($this-&gt;parameters as $var =&gt; $value)
if ($value == null || $value == '') $query .= $var.'&amp;';
else $query .= $var.'='.$value.'&amp;';
$query = substr($query, 0, -1);
$this-&gt;uri .= $query;
if (isset($this-&gt;parameters['acl']) || !isset($this-&gt;parameters['logging']))
$this-&gt;resource .= $query;
$url = (extension_loaded('openssl')?'https://':'http://').$this-&gt;headers['Host'].$this-&gt;uri;
//var_dump($this-&gt;bucket, $this-&gt;uri, $this-&gt;resource, $url);
// Basic setup
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_URL, $url);
//:callback function call for upload progress.
curl_setopt($curl, CURLOPT_NOPROGRESS, false);
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50500) {
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION,  array($this, 'progressCallback_old_curl'));
} else {
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION,  array($this, 'progressCallback_new_curl'));
// Headers
$headers = array(); $amz = array();
foreach ($this-&gt;amzHeaders as $header =&gt; $value)
if (strlen($value) &gt; 0) $headers[] = $header.': '.$value;
foreach ($this-&gt;headers as $header =&gt; $value)
if (strlen($value) &gt; 0) $headers[] = $header.': '.$value;
foreach ($this-&gt;amzHeaders as $header =&gt; $value)
if (strlen($value) &gt; 0) $amz[] = strToLower($header).':'.$value;
$amz = (sizeof($amz) &gt; 0) ? "\n".implode("\n", $amz) : '';
// Authorization string
$headers[] = 'Authorization: ' . S3Withprogressbar75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0__getSignature(
$this-&gt;verb."\n".
$this-&gt;headers['Content-MD5']."\n".
$this-&gt;headers['Content-Type']."\n".
$this-&gt;headers['Date'].$amz."\n".$this-&gt;resource
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&amp;$this, '__responseWriteCallback'));
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&amp;$this, '__responseHeaderCallback'));
// Request types
switch ($this-&gt;verb) {
case 'GET': break;
case 'PUT':
if ($this-&gt;fp !== false) {
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $this-&gt;fp);
if ($this-&gt;size &gt; 0)
curl_setopt($curl, CURLOPT_INFILESIZE, $this-&gt;size);
} elseif ($this-&gt;data !== false) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, $this-&gt;data);
if ($this-&gt;size &gt; 0)
curl_setopt($curl, CURLOPT_BUFFERSIZE, $this-&gt;size);
} else
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'HEAD':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_NOBODY, true);
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default: break;
// Execute, grab errors
if (curl_exec($curl))
$this-&gt;response-&gt;code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$this-&gt;response-&gt;error = array(
'code' =&gt; curl_errno($curl),
'message' =&gt; curl_error($curl),
'resource' =&gt; $this-&gt;resource
@curl_close($curl);
// Parse body into XML
if ($this-&gt;response-&gt;error === false &amp;&amp; isset($this-&gt;response-&gt;headers['type']) &amp;&amp;
$this-&gt;response-&gt;headers['type'] == 'application/xml' &amp;&amp; isset($this-&gt;response-&gt;body)) {
$this-&gt;response-&gt;body = simplexml_load_string($this-&gt;response-&gt;body);
// Grab S3 errors
if (!in_array($this-&gt;response-&gt;code, array(200, 204)) &amp;&amp;
isset($this-&gt;response-&gt;body-&gt;Code, $this-&gt;response-&gt;body-&gt;Message)) {
$this-&gt;response-&gt;error = array(
'code' =&gt; (string)$this-&gt;response-&gt;body-&gt;Code,
'message' =&gt; (string)$this-&gt;response-&gt;body-&gt;Message
if (isset($this-&gt;response-&gt;body-&gt;Resource))
$this-&gt;response-&gt;error['resource'] = (string)$this-&gt;response-&gt;body-&gt;Resource;
unset($this-&gt;response-&gt;body);
// Clean up file resources
if ($this-&gt;fp !== false &amp;&amp; is_resource($this-&gt;fp)) fclose($this-&gt;fp);
return $this-&gt;response;
private function __responseWriteCallback(&amp;$curl, &amp;$data) {
if ($this-&gt;response-&gt;code == 200 &amp;&amp; $this-&gt;fp !== false)
return fwrite($this-&gt;fp, $data);
$this-&gt;response-&gt;body .= $data;
return strlen($data);
private function __responseHeaderCallback(&amp;$curl, &amp;$data) {
if (($strlen = strlen($data)) <= 2) return $strlen;
if (substr($data, 0, 4) == 'HTTP')
$this-&gt;response-&gt;code = (int)substr($data, 9, 3);
else {
list($header, $value) = explode(': ', trim($data));
if ($header == 'Last-Modified')
$this-&gt;response-&gt;headers['time'] = strtotime($value);
elseif ($header == 'Content-Length')
$this-&gt;response-&gt;headers['size'] = (int)$value;
elseif ($header == 'Content-Type')
$this-&gt;response-&gt;headers['type'] = $value;
elseif ($header == 'ETag')
$this-&gt;response-&gt;headers['hash'] = substr($value, 1, -1);
elseif (preg_match('/^x-amz-meta-.*$/', $header))
$this-&gt;response-&gt;headers[$header] = is_numeric($value) ? (int)$value : $value;
return $strlen;

Here is another answer: After a lot of searching around I found the simple answer to this question is NO.
Basically the best way to do this, as I have found out from Amazons own coding (their little uploading widget on the AWS S3 console) it is only really possible to get upload progress by sending to another server first which PHP can read for progress information.
This creates a 'pass-through' policy using your own app servers /tmp directory as the stepping stone. This seems to be the preferred method.
Comment for this answer: Do you perhaps have any examples still available? I'll probably have to do a similar thing..
Comment for this answer: I managed to upload to S3 from JS via my PHP proxy. But how would I go about keeping progress bar status in JS ? no info about that anywhere..
Comment for this answer: Indeed - but how do I get progress from putObject PHP call for example? (so I can pass the data on ..)
Comment for this answer: Thanks, will get into it
Comment for this answer: No progress example here though? It looks pretty similar to putObject ...
Comment for this answer: Only very old code which I do not think is valid with their new API, basically you upload as normal to our own server and then copy either in it's full form or per chunk to S3 (using a multiple part form you can get the chunks before it is fully uploaded in PHP from the stream)
Comment for this answer: You cannot really do a progress bar in JS, you need to create an AJAX poller to the server side which responds with the progression
Comment for this answer: You don't you o multipart uploads https://docs.aws.amazon.com/aws-sdk-php/v3/guide/service/s3-multipart-upload.html you take the file size and break it into chunks and then use that to determine progress
Comment for this answer: You won't find an example, you gotta put it together yourself. This function allows you to upload in chunks to S3, if you split the file down in PHP and use this function then you can get progress while uploading the chunks you have

Here is another answer: Yes you can via multipart uploading: http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMPphpAPI.html
Multipart uploading is a three-step process: You initiate the upload, you upload the object parts, and after you have uploaded all the parts, you complete the multipart upload. Upon receiving the complete multipart upload request, Amazon S3 constructs the object from the uploaded parts, and you can then access the object just as you would any other object in your bucket.
http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html
I will be doing this personally very soon but this is what you need to start.
Comment for this answer: Any examples perhaps? I'm using JS to send to browser but credentials are plaintext, so I'll have to go with JS->proxy->S3 where proxy will be my server script. Any help appreciated
Comment for this answer: @MichaelCalkins did you ever get this accomplished?  2014 is almost done and I still can't see a clear cut answer to do this?
Comment for this answer: You still have to upload this to your own server to understand a progression since you must have the total file size on your server before you can do anything with it. Effectively you will be uploading it to your sertver first as normal and then multi part uploading to Amazon to get the upload progression which means you will actually be judging the progression of upload on your server only. I suppose you could rewrite the core PHP scripts to release upload parts that you can then upload to Amazon, howeer the PHP core does not currently do this
Comment for this answer: @Sammaye I'm actually in the middle of doing this atm and I'm having to upload to server then to S3.  Until I figure out to go straight to S3 I was going write a little hack or write to a file temporarily to send feedback for my users.  As long as you can see or use this multipart function you should be able to hook in, in one way or another.

Here is another answer: AWS PHP SDK has a code example where they show upload progress while uploading to S3. I am not sure if its valid for small files but for streaming it sure works.
You can check more out at - http://aws.amazon.com/sdkforphp/
In a way if they are showing progress - we surely can get that in the form of a progress bar with the help of a Javascript framework like jquery etc.
I shall be working on it very soon and will surely post a tutorial. Cheers!
Comment for this answer: Did you post a tutorial on this?
Comment for this answer: I would like that very much, this question was written about 4 versions ago of the sdk so I would be very much interested if things have changed and AWS does have a good way of dong this
Comment for this answer: It would be best if you could link to the specific page with the code example and not just the sdk homepage.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 5, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:04/17/12', 'FavoriteCount': 3.0, 'PostTypeId': 1, 'Tags': '<php><amazon-s3>', 'Title': 'PHP S3 upload progress', 'ViewCount': 8037, 'id': 10187653, 'user_AboutMe': '', 'user_AccountId': 162175.0, 'user_DisplayName': 'Sammaye', 'user_Reputation': 42438.0, 'user_Views': 4446.0, 'user_id': 383478.0}}