Create Google Cloud Storage Upload URLs for PHP7.2

Viewed 968

I feel like I'm missing something here, but on Google App Engine using PHP 5.5 in the standard environment I can create upload URLs very easily for my users to upload files to without wasting time in PHP, like so:

<?php
use google/appengine/api/cloud_storage/CloudStorageTools;

?><form action="<?php echo CloudStorageTools::createUploadUrl('my/upload/handler.php'); ?>" method="post">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

Enormously simplified of course (as that URL would only last 60 seconds).

However this API doesn't appear to be available to app engines running PHP 7.2, which I really need to use, and I can't seem to find an alternate API for obtaining upload URLs; have these really been discontinued?

There were other really useful features like getImageURL() for getting thumbnails and such as well. Of course a lot of the documentation still points to the above method for handling user uploads to an app engine site!

So how do I create and utilise upload URLs in the newer API?

1 Answers

Yes, you can create and utilise upload URLs with PHP 7.2 Google Client Library for Cloud Storage.

You can directly put the handler in the action attribute of the form without calling the API.

Note that in this sample you put the name of the bucket in which the files will be uploaded as an environment variable in the app.yaml file:

runtime: php72
env_variables:
  GOOGLE_STORAGE_BUCKET: <your_bucket_name>

index.php:

<?php

namespace Google\Cloud\Samples\AppEngine\Storage;

use Google\Auth\Credentials\GCECredentials;

require_once __DIR__ . '/vendor/autoload.php';

$bucketName = getenv('GOOGLE_STORAGE_BUCKET');
$projectId = getenv('GOOGLE_CLOUD_PROJECT');
$defaultBucketName = sprintf('%s.appspot.com', $projectId);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    switch ($_SERVER['REQUEST_URI']){

       case '/user/upload':
          upload_file($bucketName);
          exit;
    }
    header('Location: /');
    exit;
}
?>

<html>
  <form action="/user/upload" enctype="multipart/form-data" method="post">
            Files to upload: <br>
           <input type="file" name="uploaded_files" size="40">
           <input type="submit" value="Send">
  </form>
</html>

Handler function:

function upload_file($bucketName)
{
    $fileName = $_FILES['uploaded_files']['name'];
    $tempName = $_FILES['uploaded_files']['tmp_name'];
    move_uploaded_file($tempName, "gs://${bucketName}/${fileName}.txt");
    sprintf('Your file "%s" has been uploaded.', $fileName);
}

composer.json:

{
    "require": {
        "google/cloud-storage": "^1.5"
    },
    "require-dev": {
        "phpunit/phpunit": "^5",
        "google/cloud-tools": "^0.6"
    }
}

I suggest you clone the sample from Github and try it yourself.

Related