Uploading files to dropbox with XAMPP PHP - 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.

Related

This page contains the following errors: error on line 2 at column 1: Extra content at the end of the document

I am trying to run a server locally using ngrok to use a Twilio phone number to receive calls, but when I run ngrok http 3000 and put the url it generated the error below appears.
What can it be? All the files are giving this problem.
Erro:
<?php
// Create a route that will handle Twilio webhook requests, sent as an
// HTTP POST to /voice in our application
require_once '../vendor/autoload.php';
require_once 'Curl.class.php';
require_once './utils/Utils.php';
include '/core/DigitalLockApi.class.php';
const baseUrl = 'https://digital-lock-api-node.paymobi.com.br/';
function logText($title, $content)
{
$logfile = fopen("./log.txt", "a");
fwrite($logfile, "\n" . $title);
fwrite($logfile, "\n" . date("Y-m-d H:i:s"));
fwrite($logfile, "\n" . print_r($content, true));
fwrite($logfile, "\n" . "-----------------------------------");
fclose($logfile);
}
function initErrorsLog()
{
$log_file = "errors.log";
ini_set("log_errors", true);
ini_set('error_log', $log_file);
}
use Twilio\TwiML\VoiceResponse;
// Use the Twilio PHP SDK to build an XML response
$response = new VoiceResponse();
initErrorsLog();
if (array_key_exists('Digits', $_POST)) {
$cpf = $_POST['Digits'];
$cpfString = (string) $cpf;
if(validateCPF($cpfString)) {
$response->redirect("./password.php?cpf=$cpf");
} else {
$response->redirect('./invalidCpf.php');
}
} else {
$gather = $response->gather(['numDigits' => '100', 'timeout' => '4']);
$gather->play("https://digital-lock-api.azurewebsites.net/ura/assets/audios/insertCpf.mp3");
// If the user doesn't enter input loop
$response->redirect('./cpfNull.php');
}
// Render the response as XML in reply to the webhook request
header('Content-Type: text/xml');
echo $response;
Debugging line by line I found out that what was breaking the code was the
include '/core/DigitalLockApi.class.php';
It was not finding this import

How can I use dropbox core API in 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

Error calling DELETE - (403) Insufficient permissions for this file" | Google Drive API

I have created following code. I have to download files from my Google Drive folder. The folder is shared. After downloading, I have to delete those files from the Google Drive.
I tried -
$file = $service->parents->delete($file_id,$folder_id); - It doesn't do anything, nor does it give any error.
$file = $service->files->trash($file_id); - It gives Error calling DELETE - (403) Insufficient permissions for this file" Error.
My code :
<?php
require_once "google/google-api-php-client/src/Google_Client.php";
require_once "google/google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google/google-api-php-client/src/contrib/Google_Oauth2Service.php";
require_once "google/vendor/autoload.php";
$file_id = '1bJm_cqIRVh5RaVrqVXGRL0CSYwTBlZur';
$folder_id='1gEllj4B9TCnLPe_dnl1ujX4u8smLL-Ky';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'service_account_email#domain.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'GoogleDriveApi-7cd8056e9eae.p12';
function buildService() {//function for first build up service
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
function printFilesInFolder($service, $folderId) {
$pageToken = NULL;
$arrayFile=array();
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$children = $service->children->listChildren($folderId, $parameters);
$arrayFile=$children;
$pageToken = $children->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $arrayFile;
}
try {
$service = buildService();
$children=printFilesInFolder($service,$folder_id);
$myfile = fopen("D:/list.txt", "wb") or die("Unable to open file!");
foreach ($children->getItems() as $child) {
print "\r\nFile Id: " . $child->getId();
fwrite($myfile, $child->getId());
fwrite($myfile, "\r\n");
}
$file = $service->parents->delete($file_id,$folder_id);
$file = $service->files->trash($file_id);
fclose($myfile);
} catch (Exception $e) {
print "An error occurred1: " . $e->getMessage();
}
?>
Your error indicates that the user doesn't have a write access to the file, and an app is attempting to modify the particular file.
Suggested action: Report to the user that there is a need to ask for
those permissions in order to update the file. You may also want to
check user access levels in the metadata retrieved by
files.get and use that to change your UI to a read only UI.

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.

PHP Zend export google docs with 401 Unauthorized error message

I am running a problem with exporting a Google Docs (spreasheet) to xls file and save to our own server.
After successfully uploaded a file to Google Docs but somehow getting the 401 error message when I do the download.
Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Here is our PHP code and hope someone could help me to point out what went wrong.
Any thoughts would be highly received.
<?php
// set credentials for ClientLogin authentication
$google_user = 'xxxxx'; // Your google account username
$google_pass = 'xxxxx'; // Your google account password
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($google_user, $google_pass,$service);
$docs = new Zend_Gdata_Docs($httpClient);
// Uploading file to Google Docs works perfectly as below
//$newDocumentEntry = $docs->uploadFile('test.txt', 'order-123456','text/plain', Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);
$path = "/var/www/vhosts/googledocs";
$docsQuery = new Zend_Gdata_Docs_Query();
$docsQuery->setTitle("My Spreadsheet Name");
$docsQuery->setTitleExact(false);
$feed = $docs->getDocumentListFeed($docsQuery);
foreach ($feed->entries as $entry) {
$docID = $entry->getId();
$docTitle = $entry->getTitle();
if($entry->getTitle() == "My spreadsheet File Name"){
$strURL = $entry->content->getSrc() . '&exportFormat=xls&format=xls';
$data = $docs->get($strURL);
file_put_contents($path."test.xls", $data);
}
}
?>
UPDATE - 23/05/2012
We finally got it working by tweaking the code as below: It would be useful for someone !
foreach($feed as $entry):
if($entry->getTitle() == 'My Spreadsheet File Name'){
$path = "/var/www/vhosts/regustouchstone.com/subdomains/docs/httpdocs/googledocs";
$strURL = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=".basename($entry->id)."&exportFormat=xls&format=xls";
try{
$data = $service->get($strURL)->getBody();
$fp = fopen($path."/test.xls", "w+");
fwrite($fp, $data);
fclose($fp);
}catch(Zend_Exception $e) {
echo "<br /><br /> ERROR <br />";
echo $e->getMessage();
}
}
endforeach;
Is $strUrl correctly and consistently encoded, e.g. are all '&' being encoded as '&'?
Also, if the server for the download link is http://spreadsheets.google.com (as opposed to http://docs.google.com) you might need to authenticate to the Spreadsheet service:
$spreadsheetClient = Zend_Gdata_ClientLogin::getHttpClient($google_user, $google_pass, Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME);
$spreadSheetService = new Zend_Gdata_Spreadsheets($spreadsheetClient);
...
// download the spreadsheet
$data = $spreadSheetService->get($strURL);
We have a solution as below:
foreach($feed as $entry):
if($entry->getTitle() == 'My Spreadsheet File Name'){
$path = "/var/www/vhosts/regustouchstone.com/subdomains/docs/httpdocs/googledocs";
$strURL = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=".basename($entry->id)."&exportFormat=xls&format=xls";
try{
$data = $service->get($strURL)->getBody();
$fp = fopen($path."/test.xls", "w+");
fwrite($fp, $data);
fclose($fp);
}catch(Zend_Exception $e) {
echo "<br /><br /> ERROR <br />";
echo $e->getMessage();
}
}
endforeach;

Categories