im using php google SDK (PHP 7.2.27), The process to create signed url v4 takes >1500 ms. what i want to ask is it this normal? or something wrong with my setup? can it be optimized? the real code have caching mechanism so its solved the problem when the url already created, it will be problem if happen for the first time. here's the part of code to create signed url v4 :
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
$bucketName = <REDACTED>
$objectName = <REDACTED>
$process_time = microtime(true);
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$url = $object->signedUrl(
# This URL is valid for 15 minutes
new \DateTime('30 sec'),
[
'version' => 'v4',
'keyFilePath' => dirname(__FILE__)."/<REDACTED>.json"
]
);
$process_time = microtime(true) - $process_time;
echo "Process Time : ".$process_time."\n";
print('Generated GET signed URL:' . PHP_EOL);
print($url . PHP_EOL);
Update:
the cause is at "$storage = new StorageClient();"
using php 8.1 and its still takes >1500ms
this is snoop file of that "new StorageClient()" do :
Change
$storage = new StorageClient();
to
$storage = new StorageClient([
'projectId' => '<your_related_project_id_to_object_bucket_location>'
]);
the first one (without parameter) is an example from official document that slows down the connection about 1500ms, as someone totally new in GCP this documentation bring more confusion than clear explanation, dont use it.
Related
I have URL gs://bucket-name.appspot.com/photos/1F0CB8D1-511E-47F2-AA31-8EC131E38672.jpg,
but I need URL http://.... for show photo on site.
How I can get it? Please, explain in PHP.
What you're looking for is called a signed URL in Google Cloud Storage, and you can generate a signed URL in PHP with:
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$url = $object->signedUrl(
# This URL is valid for 15 minutes
new \DateTime('15 min'),
[
'version' => 'v4',
]
);
print('Generated GET signed URL:' . PHP_EOL);
print($url . PHP_EOL);
print('You can use this URL with any user agent, for example:' . PHP_EOL);
print('curl ' . $url . PHP_EOL);
Hi am using this OneDrive SDK . https://github.com/krizalys/onedrive-php-sdk . I am using PHP. What I need is to create a cronjob that will fetch my files in OneDrive and save it to my local directory. It works fine following the tutorial in the SDK. However, the way that SDK works is it needs you to be redirected to Microsoft account login page to be authenticated.
This will require a browser. My question, is it possible to do this by just running it in the backend like a cron? I can't seem to find a way to do it using the SDK. In Google, they will provide you a key to access the services without logging in every time. I am not sure about OneDrive.
$localPath = __DIR__.'/uploads/';
$today = date('Y-m-d');
$folder = $client->getMyDrive()->getDriveItemByPath('/'.$today);
echo "<pre>";
try {
$files = $folder->getChildren();
$createdDirectory = $localPath.$today;
// Check if directory exist
if(is_dir($createdDirectory)){
echo "\n"." Directory ".$createdDirectory." already exists, creating a new one..";
// Create new directory
$uuid1 = Uuid::uuid1();
$createdDirectory = $createdDirectory.$uuid1->toString();
echo "\n".$createdDirectory." created..";
}
// Create directory
mkdir($createdDirectory);
echo "\n".count($files)." found for ".$today;
// Loop thru files inside the folder
foreach ($files as $file){
$save = $file->download();
// Write file to directory
$fp = fopen($createdDirectory.'/'.$file->name, 'w');
fwrite($fp, $save);
echo("\n File ".$file->name." saved!");
}
} catch (Exception $e){
die("\n".$e->getMessage());
}
die("\n Process Complete!");
My code is something like that in the redirect.php
It doesn't look like that SDK supports the Client Credentials OAuth Grant. Without that, the answer is no. You may want to look at the official Microsoft Graph SDK for PHP which supports this via the Guzzle HTTP client:
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
I have the following code, modified from Google's documentation:
$GOOGLE_APPLICATION_CREDENTIALS = "./[path].json";
$_ENV["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
$_SERVER["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
$projectId = "[my project's ID']";
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/books']);
$service = new Google_Service_Books($client);
$results = $service->volumes->listVolumes('Henry David Thoreau');
Yet when I run it it returns the error:
PHP Fatal error: Uncaught exception 'DomainException' with message 'Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information'
I have tried various configurations, for example changing the path of the file. As you see, I've also done the three different forms of variables that I could immediately think of (two environment, one not).
I'm not quite sure where to look next. Should I look into different ways of setting the environment variable or should I define the path in a different way? What are the correct ways of doing this? Is there any other reason for the error?
You need to use putenv() (http://php.net/manual/en/function.putenv.php) instead of trying to use any of the methods you have used ($_ENV or $_SERVER).
Taken from https://github.com/google/google-api-php-client/blob/master/UPGRADING.md#google_auth_assertioncredentials-has-been-removed
// OR use environment variables (recommended)
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client->useApplicationDefaultCredentials();
I agree with the above answer, but only want to describe if user getting error in php using nlp google:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Language\LanguageClient;
putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/sgupta/www/practise/nlp/google/cred.json'); //your path to file of cred
//$client->useApplicationDefaultCredentials();
# Your Google Cloud Platform project ID
$projectId = 'nlp-project-nname'; //your project name
# Instantiates a client
$language = new LanguageClient([
'projectId' => $projectId
]);
# The text to analyze
$text = 'Sachin Tendulkar';
# Detects the sentiment of the text
$annotation = $language->analyzeSentiment($text);
$sentiment = $annotation->sentiment();
echo "<pre>";
print_r($annotation); die;
echo 'Text: ' . $text . '
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude'];
?>
Use this one it's working for me
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=../service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
Alternatively you can define a path to your json file like this
$client = new Google_Client();
$client->setAuthConfig('/path/to/credentials.json');
Attempt to use the ImageAnnotator like below
When running the code, observe that you get an error:
Could not construct ApplicationDefaultCredentials
solution
putenv("GOOGLE_APPLICATION_CREDENTIALS=/home/netwons/Downloads/AIz.json");
but not work.
OS: Ubuntu
PHP version: 7.2.4
Package name and version: google/cloud-vision 0.19.1
this is code
$imageAnnotator = new ImageAnnotatorClient();
// $client->setAuthConfig('key.json');
# the name of the image file to annotate
$fileName = '2.png';
# prepare the image to be annotated
$image = file_get_contents($fileName);
# performs label detection on the image file
$response = $imageAnnotator->labelDetection($image);
$labels = $response->getLabelAnnotations();
if ($labels) {
echo("Labels:" . PHP_EOL);
foreach ($labels as $label) {
echo($label->getDescription() . PHP_EOL);
}
} else {
echo('No label found' . PHP_EOL);
}
You can pass the following array to your client
[
'credentials' => json_decode(file_get_contents('path_to_your_file_.json')), true)
]
In my case its text to speech client, so it can be following
$textToSpeechClient = new TextToSpeechClient([
'credentials' => json_decode(file_get_contents('path_to_your_file.json')), true)
]);
I'm trying to use the newest Google PHP API Lib to update users and i can't find any examples on how to use it to update.
The closest example I can find is this Cannot update user information using Google PHP API Client library but it doesn't have enough info to add on to.
Below is what I have and it's copied off of another job that pulls from the users list. But that is scoped to 'https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.group.readonly https://www.googleapis.com/auth/admin.directory.orgunit.readonly'
and doesn't update anything.
I've searched and searched and cannot seem to find an example of PHP updating a user.
session_start();
require 'vendor/autoload.php';
$SCOPE = 'https://www.googleapis.com/auth/admin.directory.user';
$SERVICE_ACCOUNT_EMAIL = 'BLAHBLAH#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'blahblah.p12';
$client = new Google_Client();
$client->setApplicationName('BLahBlah.apps.googleusercontent.com');
$adminService = new Google_Service_Directory($client);
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$cred = new Google_Auth_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($SCOPE), $key);
$cred->sub = "chriswhittle#lahlah.com";
$client->setAssertionCredentials($cred);
$email = "fred#tom.com";
$requestUrl = "https://www.googleapis.com/admin/directory/v1/users/" . urlencode($email) ;
$requestMethod = 'PUT';
$data = array("title" => "Cool Guy");
$requestHeader = array('Content-Type' => 'application/json', 'Content-Length' => 'CONTENT_LENGTH');
$request = new Google_Http_Request($requestUrl, $requestMethod,$requestHeader,$data);
$httpRequest = $client->getAuth()->authenticatedRequest($request);
The code was fine, I had to go into our google apps domain security settings and grant user edit access. and adjust the body data to match the json... Here is an example.
$data = array("organizations" => array(array("name"=>"My Company","title"=>"Director, Information Technology","primary"=>true,"customType"=>"Other","department"=>"Information Technology")),"name"=>array("familyName"=> "Admin"));
This is the simple code I`m using to upload an image in my rackspace account with PHP :
<?php
$api_username = 'lolcat';
$api_key = 'sexyapi';
require 'cloudfiles.php';
$auth = new CF_Authentication($api_username, $api_key);
$auth->authenticate();
$connection = new CF_Connection($auth);
$images = $connection->create_container("pitch");
$url = $images->make_public();
echo 'The url is '.$url;
$file = 'sherlock.jpg';
$img = $images->create_object($file);
$img->load_from_filename($file)
?>
Also everytime it gives diffrent errors. Like:
"Strict standards: Only variables should be passed by reference in C:\wamp\www\cloudfiles.php on line 1969 "
" Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\cloudfiles_http.php on line 1249"
A sample of errors (imgur image)
Please help I`ve been trying this simple thing for 2 hours now.
Php-cloudfiles bindings are deprecated. I suggest you to give php-opencloud a try. I shouldn't be hard to port your code. Here's a quick example:
<?php
require 'vendor/autoload.php';
use OpenCloud\Rackspace;
$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array(
'username' => 'foo',
'apiKey' => 'bar'
));
$service = $client->objectStoreService('cloudFiles', 'DFW');
$container = $service->createContainer('pitch');
$container->enableCdn();
$cdn = $container->getCdn();
//Print "Container SSL URL: " . serialize($cdn);
$files = array(
array(
'name' => 'file_1.txt',
'body' => fopen('files/file_1.txt', 'r+')
)
);
$container->uploadObjects($files);
You can find php-opencloud docs at: https://github.com/rackspace/php-opencloud/blob/master/docs/getting-started.md