0

I couldn't find out there a PHP tutorial for storing a file in the free bucket of a Google Apps Engine project and retrieving its contents. The idea of this post is to do it step by step assuming the GAE project was correctly created.

1) If you created a GAE project it has been granted a 5Gb of a free Google Cloud Storage bucket. Its name is "YOUR_PROJECT_ID.appspot.com"

https://console.cloud.google.com/storage/browser

2) A Service Account must be created and asgigned to use the SDK.

Steps Here

3) This is the basic PHP code to store a file with a "Hello World" content. This code could be executed from the terminal windows.

<?php    

$filename = "tutorial.txt"; // filename in the bucket
$txt_toSave = "Hello Word"; // text content in the file  

// lets add code here

?>

php GCStorage_save_example.php

4) This is the basic PHP code to retrieve a file's content from the bucket.

<?php    
// lets add code here

echo $txt_fileContent;
?>

php GCStorage_retrieve_example.php

a) if permissions must be granted feel free to add the step b) if any other step must be done feel free to add it

1 Answers1

0

You can find the PHP code samples for Google Cloud Storage operations in the Official Google Cloud Storage documentation [1].

For instance, an example to store a file in Google Cloud Storage according to the documentation [2] would be:

use Google\Cloud\Storage\StorageClient;

/**
 * Upload a file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of the object.
 * @param string $source the path to the file to upload.
 *
 * @return Psr\Http\Message\StreamInterface
 */
function upload_object($bucketName, $objectName, $source)
{
    $storage = new StorageClient();
    $file = fopen($source, 'r');
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);
    printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}

You can follow the How-To [3] for retrieving an object from the bucket as well. Note that this is no different than storing/downloading objects from other buckets, as you can specify from which bucket to pull/push from.

JKleinne
  • 1,270
  • 7
  • 14