简体   繁体   中英

Loading an image from Google Cloud Bucket with PHP

Is it possible to get an image from google cloud bucket in a similar fashion to file_get_contents? I need the image for mess around with without needing to have it on my local machine/server

i have tried using the google cloud storage library for php ( https://github.com/googleapis/google-cloud-php-storage ) but it keeps giving me "failed to open stream" error, which leads me to believe that I may provided the wrong url to the file_get_content function.

I should mention that all the files are set to public, with public storage.cloud.google.com links available

My current code is similar to this:

require 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient();
$storage->registerStreamWrapper();

$contents = file_get_contents('gs://{BUCKET}/{IMAGE NAME}.jpg');

While my current bucket structure is more like this

BUCKET - FOLDER - IMAGE

I have tried adding the folder in the URL and it still gave me the same "failed to open stream" error. Could anyone point me at what am i doing wrong? Do I need to authenticate? Do I even need the library for this? I tried using file_get_content($public_url) but since storage.cloud.google.com links redirect you that obviously didn't work hahaha

Any help would be appreciated

Cheers

I have installed the Cloud SDK, and used the default service account credentials to connect to Google Cloud services link .

In general, the Google Cloud PHP library uses Service Account credentials to connect to Google Cloud services. When running on Compute Engine the credentials will be discovered automatically. When running on other environments, the Service Account credentials can be specified by providing the path to the JSON keyfile for the account (or the JSON itself) in environment variables.

  1. Run composer require google/cloud

  2. Create a test.php file:

     <?php # Includes the autoloader for libraries installed with composer require __DIR__. '/vendor/autoload.php'; # Imports the Google Cloud client library use Google\Cloud\Storage\StorageClient; # Your Google Cloud Platform project ID $projectId = 'my_project'; # Instantiates a client $storage = new StorageClient([ 'projectId' => $projectId ]); # The name for the new bucket $storage->registerStreamWrapper(); $contents = file_get_contents('gs://my-buck-sample/image.JPG'); echo 'content'. $contents. ' created.'; ?>

3.Run php test.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM