Paul Paul - 7 months ago 94
PHP Question

Google Cloud Storage File Download via PHP

I'm totally new to Google Cloud Storage (since I used Amazon S3 until now).

I want to set up my web application, so that users can download files directly from the Google Cloud Storage.
I've already tried it, using the Google Api PHP Client, but didn't get a functionally code.

I've uploaded a test file named "test.jpg" to my bucket "test-bucket-46856" which I want to download via signed url (so that users only have time limited access), but I have no idea how to get this started.

Please help. Thanks.

Answer

//Edit:

Found the perfect solution. Here the link for all others who are also searching for this solution: https://gist.github.com/stetic/c97c94a10f9c6b591883

<?php
/*
 * PHP Example for Google Storage Up- and Download 
 * with Google APIs Client Library for PHP:
 * https://github.com/google/google-api-php-client
 */

include( "Google/Client.php" );
include( "Google/Service/Storage.php" );

$serviceAccount     = "1234-xyz@developer.gserviceaccount.com";
$key_file       = "/path/to/keyfile.p12";
$bucket         = "my_bucket";
$file_name      = "test.txt";
$file_content       = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100";

$auth = new Google_Auth_AssertionCredentials(
                    $serviceAccount,
                    array('https://www.googleapis.com/auth/devstorage.read_write'),
                    file_get_contents($key_file)
                    );

$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$storageService = new Google_Service_Storage( $client );

/***
 * Write file to Google Storage
 */

try 
{
    $postbody = array( 
            'name' => $file_name, 
            'data' => $file_content,
            'uploadType' => "media"
            );
    $gsso = new Google_Service_Storage_StorageObject();
    $gsso->setName( $file_name );
    $result = $storageService->objects->insert( $bucket, $gsso, $postbody );
    print_r($result);

}      
catch (Exception $e)
{
    print $e->getMessage();
}

/***
 * Read file from Google Storage
 */

try 
{
   $object = $storageService->objects->get( $bucket, $file_name );
   $request = new Google_Http_Request($object['mediaLink'], 'GET');
   $signed_request = $client->getAuth()->sign($request);
   $http_request = $client->getIo()->makeRequest($signed_request);
   echo $http_request->getResponseBody();
}      
catch (Exception $e)
{
    print $e->getMessage();
}