I have a site that has hundred of sub-domains. I need to add these sub-domains to google search console via api and using cron job with php language script.
Can you please take a look at my code bellow and let me know what is wrong with it. There is no error message but it does not add the sub-domain to the right account. Thank you!
<?php
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
$DEVELOPER_KEY = 'My_key';
$client = new Google_Client();
$client->setApplicationName("MyProjectName");
$client->setDeveloperKey($DEVELOPER_KEY);
$client->setAuthConfig('file.json');
$scopes = array('https://www.googleapis.com/auth/webmasters');
$client->setScopes($scopes);
$url = "http://sub.example.com";
$webmasters = new Google_Service_Webmasters($client);
$webmasters->sites->add($url); // my problem is here
print_r( $webmasters->sites->listSites()); //works fine, gets back sub-domain
?>
Related
This is my current code that brings back just one project.
How can i get a list of all accessible projects?
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/../vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/../gcp-bigquery-key.json');
$scopes = implode(' ', [Google_Service_Bigquery::BIGQUERY]);
$client->setScopes($scopes);
$service = new Google_Service_Bigquery($client);
$tQ = $service->projects->listProjects();
print_r($tQ);
I see that you are using BigQuery token for as authorisation. As that key is valid for BigQuery, you are getting the project which contains that BigQuery.
For seeing all projects you can check this code found in the documentation [1]:
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('Google-CloudResourceManagerSample/0.1');
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$service = new Google_Service_CloudResourceManager($client);
$optParams = [];
do {
$response = $service->projects->listProjects($optParams);
foreach ($response['projects'] as $project) {
// TODO: Change code below to process each `project` resource:
echo '<pre>', var_export($project, true), '</pre>', "\n";
}
$optParams['pageToken'] = $response->getNextPageToken();
} while ($optParams['pageToken']);
?>
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 am trying to access my Google Drive files from a php script that will be run in a cron job, but I can't see my files.
I am using a Service account set up in Google Developpers console, which do not need authorisation interaction with the user (me).
This is my code:
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client_id = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn.apps.googleusercontent.com';
$service_account_name = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn#developer.gserviceaccount.com';
$key_file_location = 'privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Whatever");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/drive'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$parameters = array(
// 'maxResults' => 10,
);
$dr_results = $service->files->listFiles($parameters);
foreach ($dr_results as $item) {
echo $item->title, "<br /> \n";
}
It seems I am correctly connected (got token, no errors prompted), but I only get one single file listed, which is not part of my Drive, and which is named "How to get started with Drive"!
I am using latest Google APIs Client Library for PHP , with php 5.4
Google will create its own google drive for service account.
What you need to do is SHARE your folder with service's account email from console.
Give it permission "can edit".
I made a shared folder in my GUI accessible drive, then I insert the files from the commandline under this folder shared, so I see them ;)
how to retrieve a all users from a Google apps doamin . I have tried with the following coed but google return error like "Error calling GET https://www.googleapis.com/admin/directory/v1/users?domain=domainname.com: (401) Login Required "
set_include_path(get_include_path() . PATH_SEPARATOR . 'E:\wamp\www\Google APIs\google-api-php-client\src');
ini_set("memory_limit", -1);
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';
require_once 'google-api-php-client/src/Google/Service/Oauth2.php';
require_once 'google-api-php-client/src/Google/Service/Directory.php';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('42X74XXXXXercontent.com');
$client->setClientSecret('OxzVALdXwd');
$client->setRedirectUri('http://localhost/Google%20APIs/index.php');
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setDeveloperKey("AIXXXXXJDUdX48");
$SCOPES = array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
$client->setScopes($SCOPES);
$token = '{"access_token":"ya29.1.AAXXXaeTg","token_type":"Bearer","expires_in":3600,"id_token":"eyJhbXXXXXXX9cEjDMUMe6PVrgo","refresh_token":"1\/sN-XXXXX5qdIGMeEW95tJv-0a1ujWk","created":1397878356}';
$decoded = json_decode($token);
$client->setAccessToken($token);
if ($client->isAccessTokenExpired()) {
$client->refreshToken($decoded->refresh_token);
}
$adminsdk = new Google_Service_Directory($client);
$users_list = $adminsdk->users->listUsers(array('domain'='domainon.info'));
Note : I have Perform a authorization with
$SCOPES = array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
Please help me
You say you're performing the authorization for those scopes, but those scopes aren't included in the client. Make sure you include this code before you run $client->refreshToken():
$client->setScopes($SCOPES);
I have the following code
<?php
// Include DropBox API
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
// Settings for DropBox
$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authCode = \trim(\readline("A-WALID-KEY-HERE"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
?>
Bud i get this error when i run the code.
Call to undefined function readline()
What am I doing wrong?
It sounds from your comment like you're trying to run this as a web app. If so, you're going to run into trouble. This looks like the command-line app example code, which is why it uses readline (which reads input from the command-line).
You might want to start from the web-file-browser example that ships with the SDK. This is meant to be run as a web app and should show you to how to do (among other things) authentication in the browser.
I had the same problem with the same code. You have forgotten to add this:
$authorizeUrl = $webAuth->start();
just right after this line:
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
What you have to do is to use the created link stored in the variable $authorizeUrl to get the authorization code.
After doing this you need to use the authorization code to generate a token. For this comment the part of your code like that:
<?php
// Include DropBox API
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
// Settings for DropBox
//$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
//$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
//**$authorizeUrl = $webAuth->start();**
$authCode = \trim(\readline("**A-WALID-KEY-HERE**"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
?>
Once you get the token save it somewhere safe and comment also the rest of the lines. Then you can access dropbox with no problem. For example:
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();