Upload Files to Google Cloud Storage using PHP

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

Cloud Storage can be useful for many reasons. You may want to serve static content of your website from the Cloud to improve its 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 require 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 Google Cloud Storage, you need to create a service account. The service account contains the credentials that are used for authentication. Using these credentials you will 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 must enable the 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 the 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(you have chosen in previous steps). You first need to create a bucket on the Cloud Storage and then store files inside it. Let’s see how to do this.

Using the Composer command install the Google Cloud Storage package as follows.

composer require google/cloud-storage

After this, you can perform the authentication using the service account credentials as shown 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. Upon passing the authentication, you can use the Cloud Storage API to create buckets, store files in buckets, download them locally, delete files, 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”.

Read more about it on Bucket naming guidelines. For this tutorial, I am keeping the bucket name as artisansweb-bucket. The below code can be used to create a bucket.

<?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);
    $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 programmatically created the bucket in the previous step. However, it’s not compulsory to create a bucket using the code only. You can also create it manually on the Cloud dashboard.

Now let’s see how to store files inside the 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')
    );
    echo "File is uploaded successfully.";
} catch(Exception $e) {
    echo $e->getMessage();
}

The above code will upload the file to your Google Cloud Storage and only users granted permission can access this object. When other users try to access this file, it will throw permission denied or 403 forbidden error.

To make your file publicly available, you need to manage object permission using Predefined ACLs. It gives read access to anyone having the object URL. You can do it using 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';
    $fileName = '1.jpg';
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload(
        fopen($fileName, 'r'),
        [
            'predefinedAcl' => 'publicRead'
        ]
    );
    echo "File is 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. Whenever you try 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. Look at the code below written for resumable uploads.

<?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 is uploaded successfully.";
} catch(Exception $e) {
    echo $e->getMessage();
}

This code will send the given largefile.zip in chunks of 262144 bytes(around 262 kb) to Cloud Storage.

Delete File from Cloud Storage Bucket

In real-world applications, sometimes you have to delete objects from Cloud Storage. You can delete these objects with the help of the following 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();
    echo "File is deleted successfully.";
} catch(Exception $e) {
    echo $e->getMessage();
}

In this tutorial, I tried to cover basic operations using Google Cloud Storage and PHP. I hope you may learn to manage files programmatically on Google Cloud Storage using PHP. You can also check out these resources for more information – PHP Cloud Client Libraries and Google Cloud PHP Storage.

Related Articles

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

1 thought on “Upload Files to Google Cloud Storage using PHP

Leave a Reply

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