Providing Public Access to Files

A common use case is making your files publicly accessible via the web. You can do this in the PHP 5 standard environment in any of these ways:

  • Serve files in Google Cloud Storage from a script: your app serves the file.
  • Serve files from Google Cloud Storage, which serves the file directly.
  • Serving files uploaded with your app by using the static handler in app.yaml.

Note that the last methodology does not use Cloud Storage.

Serving files from a script

If you want to serve files from your app, import the App Engine CloudStorageTools class:

use google\appengine\api\cloud_storage\CloudStorageTools;

Now use CloudStorageTools::serve to serve the file from Google Cloud Storage:

CloudStorageTools::serve("gs://${my_bucket}/serve.txt");

Serving files from the app in this way allows the developer to determine user identity and ensure that only authorised users access the file. The downside to this approach is that your application needs to run this code to serve the file, which consumes instance hours and thus incurs cost.

Serving files directly from Google Cloud Storage

There is a faster and more cost-effective way to serve files than serving them from the app, as mentioned above: serving them from Cloud Storage directly via HTTP. The files need to be configured to be readable by anonymous users at file write time. As we'll show in the snippet below, you set the acl stream option to public-read.

Once the file is written to Cloud Storage as publicly readable, you need to get the public URL for the file, using CloudStorageTools::getPublicUrl.

In the following example, we create a public-readable file containing some random numbers, writing it to a Cloud Storage bucket, and redirect to that file from Cloud Storage.

$options = ['gs' => ['acl' => 'public-read']];
$context = stream_context_create($options);
$fileName = "gs://${my_bucket}/public_file.txt";
file_put_contents($fileName, $publicFileText, 0, $context);

$publicUrl = CloudStorageTools::getPublicUrl($fileName, false);

The limitation of this approach is that there is no control over who can access the file, because the file is readable by anyone.

Serving files uploaded with your app

This option is fully described under Is there any other way to read and write files.