Getting started with Google Storage - php

I am having really difficult time trying to connect Google Storage. All I need is to be able to upload PDF file to a bucket that I've created on Google Storage Console. The documentation seems to be all over the place and lacking simple examples of PHP code. So here's what I've done so far:
Installed cloud storage
$ composer require google/cloud-storage
Added billing as per Google's requirement. Enabled Cloud Storage API. Created project and added a bucket.
Attempted to use the following example:
require '../vendor/autoload.php';
define("PROJECT_ID", "my-project");
define("BUCKET_NAME", "my-bucket");
$client = new Google_Client();
$client->setApplicationName("API_Cloud_Storage");
$client->useApplicationDefaultCredentials();
$client->setScopes(["https://www.googleapis.com/auth/cloud-platform"]);
$service = new Google_Service_Storage($client);
$request = $service->buckets->listBuckets(PROJECT_ID);
foreach ($request["items"] as $bucket)
printf("%s\n", $bucket->getName());
Keep on getting error on
Fatal error: Uncaught Error: Class 'Google_Client' not found in /home/domain/public_html/test.php:11 ...
I know the vendor/autoload.php file is loading because I have no issues with AWS in a different script.
I didn't even pass the first line. What am I missing?

You have the documentation page for Cloud Storage Client Libraries with a PHP sample and detailed instructions. There's also a link to the GitHub repo for that quickstart, in addition to the one shared by ceejayoz in the comments.

Related

Google GCP error with tutorial code

Resolving the issue. My Case:
Before reading the question, my issue was solved due to my development environment. Using CodeKit (an application on MacOS), upon building my code from the source folder, items such as the composer.json and other files did not transfer causing the issues described below. If this does happen to you scout the two folder to look for discrepancies the paste the missing docs from the src to the build folder.
:: QUESTION ::
I am starting to use GCP today and after following the instructions defined here:
composer require google/cloud-storage
then:
putenv("GOOGLE_APPLICATION_CREDENTIALS=/path/to/creds.json");
require __DIR__.'/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
$myid = "my-project-id";
$storage = new StorageClient([
'projectId'=>$myid
]);
var_dump($storage->buckets());
When running this i get the following error:
Fatal error: Class 'Google\Auth\Cache\MemoryCacheItemPool' not found in /place/to/vendor/google/cloud-core/RequestWrapperTrait.php on line 94
I have no idea how to solve the issue, as i am just getting started with GCP. No idea whether this is a problem with the platform or my code.
File structure appears as follows for the Google Auth:
vendor
google
auth
src
tests
cloud-core
cloud-storage
the /Cache/MemoryCacheItemPool exists inside both the tests and src folder, but the above is referencing it minus the src or tests folder.
I have also ran:
composer update
and uninstalled and reinstalled the package to no effect
Google Cloud Project Link
Where did you find the code that you used and pasted? Because the one present in the official documentation is different.
This portion of code is the one in the tutorial you linked, try to use the client library and post the error logs if get any!
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
$projectId = 'YOUR_PROJECT_ID';
$storage = new StorageClient(['projectId' => $projectId]);
$bucketName = 'my-new-bucket';
$bucket = $storage->createBucket($bucketName);
echo 'Bucket ' . $bucket->name() . ' created.';
Remember that bucket name should be unique and therefore I would advice you to test it with a long complex name to avoid to hit already used names, and always test the result of the operation.
UPDATE
I tested also your code and it is working as well, therefore I believe that is an error in the setup of the environment.
Did you get any error while running the composer require google/cloud-storage? Because the class that is missing Google\Auth\Cache\MemoryCacheItemPool is part of Psr that is installed by the composer
[...]
Installing psr/cache (1.0.1)
Loading from cache
[...]
UPDATE2
Matthew M found the error in its configuration and posted:
Finally resolved the issue. I'm using CodeKit in my working
environment and it looks like it is changing something when it
compiles. Ran an uncompiled version and it's working fine.

Access Google Cloud Storage from Local Env PHP

I am just trying to do a very simple file_get_contents('gs://[bucket][file]');
I am getting this error when I run locally.
"\google\appengine\ext\cloud_storage_streams\CloudStorageStreamWrapper::stream_open" call failed.
However, when I run it on my production env it works fine.
I know I am missing something with the setup, and I am just not sure what.
I have set the project gcloud config set project PROJECT_ID, set the account gcloud config set account ACCOUNT, and run gcloud auth login. Any ideas on what I am missing in my setup here?
I ran composer install , composer require google/cloud, I don't get any errors when including use Google\Cloud\Storage\StorageClient; I created the service-account-keyfile as an owner of the bucket. Set owners to full permissions. Ran this code...
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'keyFilePath' => __DIR__ .'/../keys/appdocs-com.json',
]);
echo file_get_contents('gs://[myBucket][myFile]');
and I am still getting ...streamWrapper::stream_open" call failed
I even tried the service builder approach.
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\ServiceBuilder;
use Google\Cloud\Storage\StorageClient;
$gcloud = new ServiceBuilder([
'keyFilePath' => __DIR__ .'/../keys/appdocs-com.json',
'projectId' => 'appdocs-com',
]);
$storage = $gcloud->storage();
$bucket = $storage->bucket('test-appdocs-sendgrid-inbound');
$object = $bucket->object('4/envelope.json');
$stream = $object->downloadAsStream();
echo $stream->getContents();
this returns
Fatal error: Uncaught exception 'Google\Cloud\Core\Exception\ServiceException' with message 'No system CA bundle could be found in any of the the common system locations. PHP versions earlier than 5.6 are not properly configured to use the system's CA bundle by default. In order to verify peer certificates, you will need to supply the path on disk to a certificate bundle to the 'verify' request option: http://docs.guzzlephp.org/en/latest/clients.html#verify. If you do not need a specific certificate bundle, then Mozilla provides a commonly used CA bundle which can be downloaded here (provided by the maintainer of cURL): https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt. Once you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP ini setting to point to the path to the file, allowing you to omit the 'verify' request option. See http://curl.haxx.se/docs/sslcerts.html for more information.' in /Users/thom/Engine/appdocs-com/vendor/google/cloud-core/RequestWrapper.php:241 Stack trac in /Users/thom/Engine/appdocs-com/vendor/google/cloud-core/RequestWrapper.php on line 241
I have my runtime at php55. Could that be preventing me from using StorageClient or serviceBuilder
When outside the appengine environment, you will need to manually register the cloud storage stream wrapper to access files using the gs:// protocol:
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'keyFilePath' => '/path/to/service-account-keyfile.json'
]);
$storage->registerStreamWrapper();
This example assumes you have Google Cloud PHP installed.
More information is available in the Google Cloud PHP docs.
To resolve the guzzle ssh error, refer to this answer. NOTE that setting verify to false is not safe, and should only be used to test, never in production.
As #jdp mentioned in his answer, the error I was getting was related to my installation of curl.
So I looked at Google's php_ini docs to see if I could set the openssl.cafile. https://cloud.google.com/appengine/docs/standard/php/config/php_ini
If you want to use Google Storage Client you need to change from standard to flexible env.
https://cloud.google.com/appengine/docs/flexible/php/quickstart
Then read through cloud storage docs to see how to download dependencies for the API usage: https://cloud.google.com/storage/docs/reference/libraries
Once you have set up your flex env and gathered dependencies, you can then follow these directions to set up the connection.
Set up a service account key In Google Cloud Console:
Select "your-project"->IAM & ADMIN-> Service Accounts.
Click the "Create Service Account" button.
Assign role (in my case I assigned the role "owner" since this service account was specific to my local development), mark the checkbox "Furnish New Private Key".
This just downloaded your "service-account-keyfile.json"
Then in the code initiate Cloud Storage like so:
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'keyFilePath' => '/path/to/service-account-keyfile.json'
]);
$storage->registerStreamWrapper();
You can now retrieve bucket data like you would from the production env.
echo file_get_contents('gs://[Bucket][File]');
Make sure you have set the bucket permissions to allow the previously selected role to access the bucket.
However, I would still love to find a way to set up a local environment with with php standard that can interact with gs://[bucket]/[file].

Class not found in Google Cloud app

I am getting the following error:
Fatal error: Class 'Google\Cloud\Datastore\DatastoreClient' not found in /base/data/home/apps/e~brookes-room-usage/1.3998538263957262‌​38/record-usage.php on line 84
so presumably I have failed to point my app correctly to that class.
I have enabled the Datastore API on the cloud console.
I have tried to find documentation relating to how to set up a PHP connection to the Datastore API.
I tried to create a settings.yml file using the instructions here but I didn't know what my client ID or my client secret were.
# Google credentials and configuration
google_client_id: YOUR_CLIENT_ID
google_client_secret: YOUR_CLIENT_SECRET
google_project_id: YOUR_PROJECT_ID
# options are "cloudsql", "mongodb", or "datastore"
bookshelf_backend: datastore
(source on Github)
What do I need to get my PHP app on Google Cloud to recognise Google\Cloud\Datastore\DatastoreClient and connect to the Datastore API so that I can retrieve and post data?
I think you forgot to include google/cloud-datastore library. Install via composer as below.
$ composer require google/cloud-datastore
and you can use as below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Datastore\DatastoreClient;
$datastore = new DatastoreClient([
'projectId' => 'my_project'
]);
// Create an entity
$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = 'bob#example.com';
$datastore->insert($bob);
// Update the entity
$bob['email'] = 'bobV2#example.com';
$datastore->update($bob);
// If you know the ID of the entity, you can look it up
$key = $datastore->key('Person', '12345328897844');
$entity = $datastore->lookup($key);
More details: https://github.com/GoogleCloudPlatform/google-cloud-php#google-cloud-datastore-ga
I am already using this and working fine for me.
So it turns out that you can only run PHP with Datastore on a Google Cloud app on your local device, not on Google Appengine, unless you use a third-party library.
Which is why I am now writing my app in Python instead.
(Update: this may no longer be the case. This answer was written in 2017.)

Mailgun SDK unable to find required classes (php)

I'm trying to use the Mailgun API SDK to send emails from my test server. I downloaded the SDK itself as I am not currently using Composer.
However, when I try to instantiate a Mailgun object, I get this error:
Fatal error: Class 'Mailgun\Connection\RestClient' not found in /var/www/mysite.xyz/www/inc/libs/Mailgun/Mailgun.php on line 38
Which I fixed by adding require "Connection/RestClient.php"; to the Mailgun.php file. However, this in turn caused its own error.
Fatal error: Class 'GuzzleHttp\Client' not found in /var/www/mysite.xyz/www/inc/libs/Mailgun/Connection/RestClient.php on line 41
This is included in my includes.php, so for all pages.
#Mailgun php functions
require_once "libs/Mailgun/Mailgun.php";
use Mailgun\Mailgun;
Then, when I try to use this;
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun\Mailgun("key-myactualkey");
$domain = "myactualdomain.xyz";
print "Email to send is ".$welcomeemail; #Never gets reached
It causes those fatal errors and the program grinds to a halt.
Why is this happening and how do I fix it?
I had the same problem and fixed it by using composer which is easier then you might think. Just follow these instructions (locally, on your computer, where PHP should be installed):
https://github.com/mailgun/mailgun-php/blob/master/SharedHostInstall.md
Then upload all files generated to your server in a separate directory.
Then include the following lines to your script:
require 'your/path/to/these/files/vendor/autoload.php';
use Mailgun\Mailgun;
Create a new Mailgun object like this:
$mg = new Mailgun("your-secret-key");

Guide me implementing OAuth2 storage classes in thephpleague library

I am developing an oAuth 2.0 server using thephpleague library provided by Alex Bilbie. But, after the initializing the authorization server, when I declare the storage classes it throws an following error.
"Fatal error: Class 'Storage\SessionStorage' not found"
Please help me to resolve this. I read your post about this problem here:- Guide me implementing Oauth2 PHP server using thephpleague library
Please let me know how can I implement the storage classes. My current code:
require_once "/../vendor/autoload.php";
$server = new \League\OAuth2\Server\AuthorizationServer;
$server->setSessionStorage(new Storage\SessionStorage);
$server->setAccessTokenStorage(new Storage\AccessTokenStorage);
$server->setClientStorage(new Storage\ClientStorage);
$server->setScopeStorage(new Storage\ScopeStorage);
$server->setAuthCodeStorage(new Storage\AuthCodeStorage);
$authCodeGrant = new \League\OAuth2\Server\Grant\AuthCodeGrant();
$server->addGrantType($authCodeGrant);
The library that you use requires implementing your own storage classes, see http://oauth2.thephpleague.com/implementing-storage-interfaces/. The class names that you use are from an example implementation https://github.com/thephpleague/oauth2-server/tree/master/examples/relational/Storage that uses Capsule as its storage backend. If you want to use Capsule as you backend, you'll need to download those example implementation classes and install https://github.com/illuminate/database.

Categories