Mount GCP storage as filesystem, and access with php

Phanix
·
·
IPFS
·

Mainly using the gcsfuse tool, and the Google\Cloud\Storage\StorageClient kit

mount as filesystem

Google cloud plateform provides gcsfuse, a tool that can mount bucket storage to the file system, as follows;

 $ export GCSFUSE_REPO=gcsfuse-`lsb_release -c -s`
$ echo "deb http://packages.cloud.google.com/apt $GCSFUSE_REPO main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list
$ curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install gcsfuse
$ sudo mkdir /photovideo
$ sudo gcsfuse photovideo /photovideo/
$ sudo ls -al /photovideo-ulsee

It's easy to unmount

 $ fusermount -u /home/shared/local_folder/

access with php

To access through php, you need to use google api, which can be found here , and can be installed through composer.
The more tedious part is the access authentication part. Although the cloud sdk is installed on the machine, it can be read and written directly like alibabacloud oss after it is mounted. However, Google does not recommend this use, mainly because it is afraid that the entire storage will be seen after being broken, so it is recommended to do it through the api (refer to the Authentication Guide ).

Follow the Authentication Guide to generate a key in json format and save it. For example, there is an upper-level path to call the php file, which is ../service_api_key.json, and then you can reference the google cloud storage library and access the storage space through this keyfile.

 <?php
require '../vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\ServiceBuilder;
....
....
class UploadsController extends ControllerBase
{
    public function test()
    {
//....
//....
        $storage = new StorageClient([
            'keyFilePath' => '../service_api_key.json'
        ]);
        $storage->registerStreamWrapper();


        $files[0]->moveTo($this->storageconfig->tmp . $upload->upload1);

        exec("sudo mv " . $this->storageconfig->tmp . $upload->upload1 . " " . $this->storageconfig->upload . $upload->upload1);

//....
//....

        // read file
        $target_file_gs = "gs://gcp-test-storage/source/". $upload->upload1;
        readfile($target_file_gs);
    }
}

Mainly through the new StorageClient and give the key file, and then call registerStreamWrapper () to obtain access rights. The strange thing is that when uploading as a file, it must be saved to the local file and then moved to the gcp storage, so remember to open the sudo mv permission of the www server at the same time.

Original link: Phanix's Blog

CC BY-NC-ND 2.0

Like my work? Don't forget to support and clap, let me know that you are with me on the road of creation. Keep this enthusiasm together!