Please note that the contents of this offline web site may be out of date. To access the most recent documentation visit the online version .
Note that links that point to online resources are green in color and will open in a new window.
We would love it if you could give us feedback about this material by filling this form (You have to be online to fill it)



Providing Public Access to Files

A common use case is making your files publically accessible via the web. You can do this in App Engine PHP apps in any of these ways:

  • Serve files in GCS from a script (your app serves the file).
  • Serve files from GCS (GCS serves the file directly).
  • Serving files uploaded with your app, (using the static handler in app.yaml ).

Note that the last methodology does not use GCS.

Serving files from a script

If you want to serve files from your app, you must write a script that serves the file from GCS as follows:

<?php
CloudStorageTools::serve('gs://scores/today.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 GCS 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 GCS as publically readable, you need to get the public URL for the file, using the CloudStorageTools::getPublicUrl() method.

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

<?php
require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
use google\appengine\api\cloud_storage\CloudStorageTools;

$object_url = 'gs://my-bucket/'.time().rand(0,1000).'.txt';
$options = stream_context_create(['gs'=>['acl'=>'public-read']]);

$my_file = fopen($object_url, 'w', false, $options);
for($i=0;$i<900;$i++) {
  fwrite($my_file, 'Number '.$i.' - '.rand(0,1000).'\n');
}
fclose($my_file);

$object_public_url = CloudStorageTools::getPublicUrl($object_url, false);

header('Location:' .$object_public_url);

The limitation of this approach is that there is no control over who can access the file, since 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 .

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.