Upload Files to Google Cloud Storage using PHP

Google Cloud Storage is a service for storing your objects. Here the objects can be anything like images, zip, spreadsheets, PDF, or any document. Storing data on the Cloud has always been recommended for disaster recovery.

Cloud Storage can be useful in various scenarios. Serving static content of your website from the Cloud helps to improve the performance. You can store your images, PDFs on the cloud and call them on your website. It saves you bandwidth as the static content is served from an external server(Cloud server).

While working on the application, you might want to store your files programmatically on Cloud Storage. In this article, I show you how one can store their files to Google Cloud Storage using PHP.

To interact with Cloud Storage, you need to create a service account for authentication. Using its credentials we would be able to use Google Cloud services.

Creating a Service Account

Follow the steps below to create your service account and download the file containing your credentials.

Create a service account:

  • In the Cloud Console, go to the Create service account page.
  • Select a project.
  • In the Service account name field, enter a name. The Cloud Console fills in the Service account ID field based on this name. In the Service account description field, enter a description.
  • Click Create.
  • Click the Select a role field. Under Quick access, click Basic, then click Owner.
  • Click Continue.
  • Click Done to finish creating the service account.

Create a service account key:

  • In the Cloud Console, click the email address for the service account that you created.
  • Click Keys.
  • Click Add key, then click Create new key.
  • Click Create. A JSON key file is downloaded to your computer.
  • Click Close.

Apart from this, on the selected project, you need to enable Cloud Storage API via the API Library section. Copy the downloaded JSON file into your project directory. Store this file in a safe place. You should also remove it from git commit using the .gitignore.

Upload Files to Google Cloud Storage

On the Google Cloud Platform, you store objects in containers called buckets. These buckets are associated with the project chosen in previous steps. Having said that, we first need to create a bucket on the Cloud Storage and then store files inside it. Let’s see it in action.

Using the composer command install the Cloud Storage package as follows.

composer require google/cloud-storage

After this, do the authentication using service account credentials like below.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Storage\StorageClient;

try {
    $storage = new StorageClient([
        'keyFilePath' => 'JSON_KEY_FILE_PATH',
    ]);
} catch(Exception $e) {
    echo $e->getMessage();
}

If everything is followed correctly, you should not get any exceptions. Now you can use the power of Cloud Storage API to create buckets, store files to buckets, download them locally, etc.

Create a Bucket on Cloud Storage

When creating buckets in Cloud Storage you should follow naming guidelines. Your bucket names must satisfy the following requirements.

  • Bucket names must contain only lowercase letters, numbers, dashes, underscores, and dots. Spaces are not allowed.
  • Bucket names must start and end with a number or letter.
  • Bucket names must contain 3-63 characters. Names containing dots can contain up to 222 characters, but each dot-separated component can be no longer than 63 characters.
  • Bucket names cannot be represented as an IP address in dotted-decimal notation.
  • Bucket names cannot begin with the “goog” prefix.
  • Bucket names cannot contain “google” or close misspellings, such as “g00gle”.

You may read more about it on Bucket naming guidelines. For this tutorial, I am keeping the bucket name as ‘artisansweb-bucket’. Our code to create a bucket will be:

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Storage\StorageClient;

try {
    $storage = new StorageClient([
        'keyFilePath' => 'JSON_KEY_FILE_PATH',
    ]);

    $bucketName = 'artisansweb-bucket';
    $bucket = $storage->bucket($bucketName);
    if (!$bucket->exists()) {
        $response = $storage->createBucket($bucketName);
        echo "Your Bucket $bucketName is created successfully.";
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

Upon creating a bucket, you can get bucket information with the info() method.

// if you want to print bucket information
$info = $bucket->info();
print_r($info);

Upload File to Cloud Storage Bucket

We have created the bucket in the previous step. Now let’s see how to store files inside this bucket. For instance, I am sending an image ‘1.jpg’ to Cloud Storage.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Storage\StorageClient;

try {
    $storage = new StorageClient([
        'keyFilePath' => 'JSON_KEY_FILE_PATH',
    ]);

    $bucketName = 'artisansweb-bucket';
    $fileName = '1.jpg';
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload(
        fopen($fileName, 'r')
    );
} catch(Exception $e) {
    echo $e->getMessage();
}

The above code will send the file on your Google Cloud Storage and only users granted permission can access this object.

To make your file publicly available, you need to manage object permission using Predefined ACLs. It gives read access to anyone with the URL. You can do it through the code shown below.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Storage\StorageClient;

try {
    $storage = new StorageClient([
        'keyFilePath' => 'JSON_KEY_FILE_PATH',
    ]);

    $bucketName = 'artisansweb-bucket';
    $fileName = '1.jpg';
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload(
        fopen($fileName, 'r'),
        [
            'predefinedAcl' => 'publicRead'
        ]
    );
    echo "File uploaded successfully. File path is: https://storage.googleapis.com/$bucketName/$fileName";
} catch(Exception $e) {
    echo $e->getMessage();
}

Now you can access your object through the URL printed in the above code. If you want to download your bucket object locally then it can be done by the following code.

$object = $bucket->object($fileName);
$object->downloadToFile('2.jpg'); // pass the name for your downloaded local file

Performing Resumable Uploads

Sometimes you are dealing with large files. To upload large files on Cloud Storage you should make a resumable upload request. This protocol allows you to resume an upload operation after a communication failure interrupts the flow of data. Have a look at the code below.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Storage\StorageClient;

try {
    $storage = new StorageClient([
        'keyFilePath' => 'JSON_KEY_FILE_PATH',
    ]);

    $bucketName = 'artisansweb-bucket';
    $bucket = $storage->bucket($bucketName);
    $fileName = 'largefile.zip';
    $chunkSize = 262144; // chunk in bytes

    $options = [
        'chunkSize' => $chunkSize,
    ];

    $uploader = $bucket->getResumableUploader(
        fopen($fileName, 'r'),
        $options
    );

    try {
        $object = $uploader->upload();
    } catch (GoogleException $ex) {
        $resumeUri = $uploader->getResumeUri();
        $object = $uploader->resume($resumeUri);
    }

    echo "File uploaded successfully.";
} catch(Exception $e) {
    echo $e->getMessage();
}

This code will send ‘largefile.zip’ in the chunks of 262144 bytes to Cloud Storage.

Delete File from Cloud Storage Bucket

Whatever files are uploaded inside the bucket are called ‘object’. You can delete the object through the below code. Make sure to pass bucket and file names correctly.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Storage\StorageClient;

try {
    $storage = new StorageClient([
        'keyFilePath' => 'JSON_KEY_FILE_PATH',
    ]);

    $bucket = $storage->bucket('BUCKET_NAME');
    $object = $bucket->object('FILE_NAME');

    $object->delete();
} catch(Exception $e) {
    echo $e->getMessage();
}

I hope you may learn to upload files to Google Cloud Storage using PHP. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *