s3-sign.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. require 'vendor/autoload.php';
  3. header('Access-Control-Allow-Origin: *');
  4. header("Access-Control-Allow-Headers: GET");
  5. // CONFIG: Change these variables to a valid region and bucket.
  6. $awsEndpoint = getenv('COMPANION_AWS_ENDPOINT') ?: null;
  7. $awsRegion = getenv('COMPANION_AWS_REGION') ?: 'eu-west-2';
  8. $bucket = getenv('COMPANION_AWS_BUCKET') ?: 'uppy-test';
  9. // Directory to place uploaded files in.
  10. $directory = 'uppy-php-example';
  11. // Create the S3 client.
  12. $s3 = new Aws\S3\S3Client([
  13. 'version' => 'latest',
  14. 'endpoint' => $awsEndpoint,
  15. 'region' => $awsRegion,
  16. ]);
  17. // Retrieve data about the file to be uploaded from the request body.
  18. $body = json_decode(file_get_contents('php://input'));
  19. $filename = $body->filename;
  20. $contentType = $body->contentType;
  21. // Prepare a PutObject command.
  22. $command = $s3->getCommand('putObject', [
  23. 'Bucket' => $bucket,
  24. 'Key' => "{$directory}/{$filename}",
  25. 'ContentType' => $contentType,
  26. 'Body' => '',
  27. ]);
  28. $request = $s3->createPresignedRequest($command, '+5 minutes');
  29. header('content-type: application/json');
  30. echo json_encode([
  31. 'method' => $request->getMethod(),
  32. 'url' => (string) $request->getUri(),
  33. 'fields' => [],
  34. // Also set the content-type header on the request, to make sure that it is the same as the one we used to generate the signature.
  35. // Else, the browser picks a content-type as it sees fit.
  36. 'headers' => [
  37. 'content-type' => $contentType,
  38. ],
  39. ]);