Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Saving uploaded files to custom S3 key with PHP

Saving uploaded files to custom S3 key with PHP

  1. install dependencies via composer
  2. replace Uploadcare API keys in config.php
  3. replace AWS keys in config.php
  4. set your bucket name in config.php
  5. run the example
  6. upload files and check S3 bucket for copied files :)
"name": "uploadcare/custom-s3",
"description": "Custom S3 storage example",
"license": "MIT",
"authors": [
"name": "Dmitry Mukhin",
"email": ""
"repositories": [{
"type": "vcs",
"url": ""
"minimum-stability": "dev",
"require": {
"uploadcare/uploadcare-php": "dev-master",
"aws/aws-sdk-php": "2.*"
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
define('AWS_ACCESS_KEY_ID', '** your ID here **');
define('AWS_SECRET_ACCESS_KEY', '** your KEY here **');
$bucket = '** name of your S3 bucket **';
require_once 'config.php';
require_once 'vendor/autoload.php';
use Uploadcare\Api;
use Aws\S3\S3Client;
function handle_uploads() {
global $ucAPI, $bucket;
$s3Client = S3Client::factory(array(
$uuid = $_POST['images'];
$group = $ucAPI->getGroup($uuid);
$username = $_POST['username'];
// iterage over all uploaded files
foreach($group->getFiles() as $file) {
// s3 object key: e.g.: user1/image_{uuid}
$key = $username . '/image_' . $file->getFileId();
// this request creates a copy of uploaded file in the bucket
$res = $s3Client->upload(
// debug output :)
// var_dump($res);
// do something more useful here, i.e. redirect to success page
echo "files are succesfully copied to S3 bucket: $bucket";
if(isset($_POST['images'])) {
<!DOCTYPE html>
<meta encoding='utf-8'>
<?php echo $ucAPI->widget->getScriptTag(); ?>
<script type="text/javascript">
$ = uploadcare.jQuery;
$(function() {
$('#uc-form').submit(function() {
if (!$('#uc-form input[name=images]').val()) {
alert("Upload at least 1 file!");
return false;
<form method="post" action="" id="uc-form">
Username: <input type="text" name="username" value="user<?php echo rand(1, 10) ?>" /><br />
Images: <?php echo $ucAPI->widget->getInputTag('images', array('data-multiple' => 'true')); ?><br />
<input type="submit" value="Upload!" />

This comment has been minimized.

Copy link

theemstra commented Dec 28, 2016

Thanks for your gist.
This is cool, but do you have any idea if it's possible to upload the files directly to S3, without saving the file to the filesystem first?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.