How can I use dropbox core API in php - php

I am trying to use Dropbox core API in php (https://www.dropbox.com/developers-v1/core/start/php) but I am stuck while running following code solution given on stack overflow
<?php
require_once "dropbox-php-sdk-1.1.6/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
$dropbox_config = array(
'key' => 'your_key',
'secret' => 'your_secret'
);
$appInfo = dbx\AppInfo::loadFromJson($dropbox_config);
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "<br>";
echo "2. Click \"Allow\" (you might have to log in first).<br>";
echo "3. Copy the authorization code and insert it into $authCode.<br>";
$authCode = trim('DjsR-iGv4PAAAAAAAAAAAbn9snrWyk9Sqrr2vsdAOm0');
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
echo "Access Token: " . $accessToken . "<br>";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
// Uploading the file
$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);
// Get file info
$file = $dbxClient->getMetadata('/working-draft.txt');
// sending the direct link:
$dropboxPath = $file['path'];
$pathError = dbx\Path::findError($dropboxPath);
if ($pathError !== null) {
fwrite(STDERR, "Invalid <dropbox-path>: $pathError\n");
die;
}
// The $link is an array!
$link = $dbxClient->createTemporaryDirectLink($dropboxPath);
// adding ?dl=1 to the link will force the file to be downloaded by the client.
$dw_link = $link[0]."?dl=1";
echo "Download link: ".$dw_link."<br>";
?>
When I Run this code I got this error
I am commenting some code from dropbox core API which is in
dropbox-php-sdk-1.1.6/lib/Dropbox/RequestUtil.php to run dropbox core API in 5.6 php version
if (strlen((string) PHP_INT_MAX) < 19) {
// Looks like we're running on a 32-bit build of PHP. This could cause problems because some of the numbers
// we use (file sizes, quota, etc) can be larger than 32-bit ints can handle.
throw new \Exception("The Dropbox SDK uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=" . ((string) PHP_INT_MAX) . "). Library: \"" . __FILE__ . "\"");
}

Dropbox v1 API has been shutdown on September 28, 2017. The library you are trying to use is made for this retired v1.
You should use one of the v2 PHP libraries instead:
dropbox-php-sdk by Kunal Varma
dropbox-v2-php by Alorel

FYI, API v1 is being retired, so it will return a 400 error with this message: {“error”: “v1_retired”}. This means your work/code relying on API v1 endpoints may stop working.
I think you have not migrated to v2, check out the migration guide for more details.
https://www.dropbox.com/developers/reference/migration-guide

Related

Google Cloud API - Application Default Credentials

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)
]);

Download the file from dropbox?

I would like to download a csv file from my dropbox through php to my server.
I tried to use Dropbox API but I cannot get the positive result. I have downloaded the dropbox, installed it on my server and used one of the examples given:
<?php
# Include the Dropbox SDK libraries
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("app-info.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
$authCode = \trim(\readline("the_authentication_code_from_dropbox"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
$f = fopen("working-draft.txt", "w+b");
$fileMetadata = $dbxClient->getFile("/working-draft.txt", $f);
fclose($f);
print_r($fileMetadata);
?>
But this code does not retrieve my file :( Any help would be kindly appreciated :)

Dropbox API - Call to undefined function readline()

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();

Uncaught exception 'Exception' with message 'The Dropbox SDK uses 64-bit integers

How can I solve the problem with this error? I am using xampp and php 5.5.6 for my application. My code is as follow:
<?php
`enter code here`# Include the Dropbox SDK libraries
require_once "dropbox-php-sdk-1.1.2/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("app-info.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = \trim(\readline("Enter the authorization code here: "));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
// uploading files
$f = fopen($_FILES["file"]["name"], "rb");
$result = $dbxClient->uploadFile($_FILES["file"]["name"], dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);`enter code here`
?>
When I run the script on my browser, I get this error.
From the README:
Requirements:
PHP 5.3+, with 64-bit integers.

Uploading files to dropbox with XAMPP PHP

I am trying to upload files to dropbox. I am on Windows and using XAMPP. This is what I have.
# Include the Dropbox SDK libraries
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("../view/configs/json_config.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "MyApp");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
// $fp=fopen("php://stdin", "r");
// $in=fgets($fp,4094);
// fclose($fp);
define('STDIN',fopen("C://xampp/php/php.exe", "r"));
if (PHP_OS == 'WINNT') {
echo '$ ';
$line = trim(fgets(STDIN)); // reads one line from STDIN
//$line = stream_get_line(STDIN, 1024, PHP_EOL);
//$read = str_replace("\r\n", "", $in);
}
else {
//$line = readline('$ ');
$line = str_replace("\n", "", $in);
}
//$authCode = \trim(\readline("Enter the authorization code here: "));
list($accessToken, $dropboxUserId) = $webAuth->finish($line);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "MyApp");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);
$folderMetadata = $dbxClient->getMetadataWithChildren("/");
print_r($folderMetadata);
$f = fopen("working-draft.txt", "w+b");
$fileMetadata = $dbxClient->getFile("/working-draft.txt", $f);
fclose($f);
print_r($fileMetadata);
which I found here
Now I am already having problems trying to execute this code as this code originally uses the readline function (or library) which is not supported on windows. I found a substitute that I am trying to use but it doesn't work.
Currently, this is the error I am getting:
"Uncaught exception 'Dropbox\Exception_BadRequest' with message ' in ....\RequestUtil.php on line 251."
I have no idea how to get this working. Has anyone done this successfully on windows using XAMPP?
The error here makes sense... it looks like your code tries to read the contents of php.exe, which doesn't sound like a good idea. :-) That's why the string is "... This program cannot be run in DOS mode."
But if you don't redefine STDIN, $line = trim(fgets(STDIN)) looks reasonable. What happens when you run that?
It's throwing an exception because there is something wrong with your request to DropBox.
To get more debugging information, place all of your DropBox method calls within a try/catch block, for example:
try
{
$authorizeUrl = $webAuth->start();
}
catch (dbx\WebAuthException_BadRequest $e) {
var_dump($e); // Will returned detailed information about the error
}
this should start you on the right track in determining the cause.

Categories