EzDevInfo.com

dropbox-php

Dropbox client library for PHP Dropbox-PHP

List files in dropbox folder

Im having problems with the dropbox API.

When i try to get the metadata for my folder, i get the data output like this:

{"hash":"10f86b5b7c9c9276501f67a71ecd41c9","thumb_exists":false,"bytes":0,"path":"\/","is_dir":true,"size":"0 bytes","root":"app_folder","contents":[{"revision":7,"rev":"7069e0896","thumb_exists":true,"bytes":19749,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:50:43 +0000","path":"\/1_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"19.3 KB"},{"revision":6,"rev":"6069e0896","thumb_exists":true,"bytes":15797,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:51:09 +0000","path":"\/2_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"15.4 KB"},{"revision":5,"rev":"5069e0896","thumb_exists":true,"bytes":13349,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:51:26 +0000","path":"\/3_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"13 KB"},{"revision":4,"rev":"4069e0896","thumb_exists":true,"bytes":8838,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:51:46 +0000","path":"\/4_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"8.6 KB"},{"revision":3,"rev":"3069e0896","thumb_exists":true,"bytes":99646,"modified":"Tue, 20 Mar 2012 04:57:58 +0000","client_mtime":"Tue, 20 Sep 2011 14:14:26 +0000","path":"\/bg.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"97.3 KB"}],"icon":"folder"}

My problem is that i would like get the output for each the image/file name only.. But i can find the right way to do it.. i through i could do it this way:

$info = json_encode($dropbox->getMetaData(''));
foreach($info->contents->path as $file){
    echo $file;
}

But i get this error:

Warning: Invalid argument supplied for foreach() in /home/djrasmusp/rasmusp.com/db/index.php on line 16

But is there anyone that can give me a helping hand with my problem?


Source: (StackOverflow)

Dropbox php api issues

I keep getting issues with dropbox php api, i am just trying to get it to work using getmeta. but i keep getting the following error??

I think the issues is here.

public function getToken($email, $password) {

        throw new Dropbox_Exception('This API method is deprecated as of the version 1 API');

    }

here is my code.

$consumerKey = 'oksergerg1x1r';
$consumerSecret = 'zexb0rg6h54tgzzb';

require($_SERVER['DOCUMENT_ROOT'] . '/wp/includes/Dropbox/autoload.php');

//session_start();
$oauth = new Dropbox_OAuth_Wordpress($consumerKey, $consumerSecret);

echo "<pre>";
print_r($oauth);
echo "</pre>";

// If the PHP OAuth extension is not available, you can try
// PEAR's HTTP_OAUTH instead.
// $oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);

$dropbox = new Dropbox_API($oauth);

$tokens = $dropbox->getToken('mrhandsome@example.org', 'secretpassword');

// You are recommended to save these tokens, note that you don't
// need to save the username and password, so just ask your user the 
// first time and then destroy them.

echo "Tokens:\n";
print_r($tokens);

so i says that the getToken function has depreciated so what are we supposed to use instead??

UPDATE

Ok sorry googled abit and i see that the new version does not support getTokens anymore even though they are in the examples still for some reason.

So i am confused now.

I am trying to setup an app so people can enter their dropbox email and password. Then it will pull all their metadata in from their account.

With the new code how do i give a user access? if their is no email and password how do i get their correct tokens???

Sorry i am really confused with this now been working for the past two days trying to suss this.


Source: (StackOverflow)

Advertisements

Dropbox API, renaming and unique IDs

I know this has been touched upon in this post, but I was hoping for some additional clarification about this.

Currently, with the Dropbox Core API, there doesn't seem to be a way to track files that have been renamed. For example, if you're using the API to sync a Dropbox app_folder with a local application directory. You rename the file on the Dropbox side and then call delta to see how you should update your local application directory, you're returned two entries...

array(
    0 => '/somefile.txt',
    1 => null
),
array(
    0 => '/somefile-renamed.txt',
    1 => array(
        'revision' => 343
        'rev' => 'd90se4c661'
        'thumb_exists' => false
        'bytes' => 1263
        'modified' => 'Tue, 09 Apr 2013 19:06:39 +0000'
        'client_mtime' => 'Tue, 09 Apr 2013 18:43:06 +0000'
        'path' => string '/somefile-renamed.txt'
        'is_dir' => false
        'icon' => 'page_white_text'
        'root' => 'app_folder'
        'mime_type' => 'application/octet-stream'
        'size' => '1.2 KB'
    )
)

For each array returned, the first element is the file that requires an update and the second element is the file metadata info. If the second element is null, you should delete your local version (and anything under it, if it's a directory) of that file.

So, in the above example, it's telling you to delete the first file and upload this completely new file. Unfortunately, there's no way to track that this new file that you have been told to create was actually just the renamed version of the file you're being told to delete. From your application's perspective (the non-Dropbox side), it just looks like a strait delete and a new file coming in.

This can be problematic if you're storing the data in these files elsewhere (like in a database) and you need to update the record instead of creating a new record and deleting the old one.

Is there some accepted way to track file association after a rename? I can't seem to find a way to do it using metadata, delta or revisions.


Source: (StackOverflow)

Get Info OAuth Dropbox API in PHP

I am trying to get the request token from Dropbox.

Till now I have tried countless libraries, some don't work, some are not maintained, and some simply you don't know what to do. So I think it'll be easier for me to make my own functions by using OAuth and PHP.

I have collected some knowledge from a few places and created this:

<?php
$consumer = new OAuth("Key", "Secret", OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);

$consumer->fetch('https://api.dropbox.com/1/oauth/request_token', null, OAUTH_HTTP_METHOD_POST);

?>

And it seems to work.

Now my questions are:

  1. I want to know how do I get the stuff they have sent in return, i.e. the Request Token?
  2. And will I be able to use this method for other things too, like getting Access Tokens and more?

Note: I'm on Ubuntu 12.04 with the OAuth PHP5 Library installed using PECL.


Source: (StackOverflow)

How to create folder(if not exist) in dropbox accout using php-api?

am trying to learn dropbox php-api. i have done upload, but unable to create a new folder(if not exist) in dropbox account

code snippet :

// Create new directory
$create_new_folder = $dropbox->createFolder('new_folder','dropbox');

// Create a temporary file and write some data to it
$tmp = tempnam('/tmp', 'dropbox');
$data = 'This file was uploaded using the Dropbox API!';
file_put_contents($tmp, $data);

// Upload the file with an alternative filename
$put = $dropbox->putFile($tmp, 'abc.txt');

// Unlink the temporary file
unlink($tmp);

// Dump the output
var_dump($put);

error:

Call to undefined method Dropbox\API::createFolder() in C:\wamp\www\BenTheDesigner-Dropbox-b49576c\examples\putFile.php on line 18


Source: (StackOverflow)

Newly Generated Dropbox Token Expires Instantly

I am having this weird issue here in which the instant I get a token via Dropbox and try to test it, an exception is thrown with this message:

HTTP status 401 {"error": "The given OAuth 2 access token doesn't exist or has expired."}

Why would a Dropbox token expire as soon as I generate it?

Let me show you the flow of my app:

User sees this screen:

Form 1

Which has the following relevant PHP code:

require "../../includes/dropbox-sdk/Dropbox/autoload.php";
require "../../includes/config.php";
session_start();
session_regenerate_id();
$appInfo = Dropbox\AppInfo::loadFromJsonFile("../../includes/dropbox-sdk/Dropbox/app-info.json");
$webAuth = new Dropbox\WebAuthNoRedirect($appInfo, "Mignori-Box/1.0");

$authorizeUrl = $webAuth->start();

So okay, we generate a Dropbox authorization URL with the official SDK, which seems to be working fine, the user sees this screen:

Dropbox

They click allow, Dropbox gives them an Authorization token, then they paste it into my site, and submit it. This is the code that processes the form:

      try
      {
          $accessToken = $_POST['authorization_code'];

          $dbxClient = new Dropbox\Client($accessToken, "Mignori-Box/1.0");
          $accountInfo = $dbxClient->getAccountInfo();
      }catch(Exception $e)
      {
          echo "<div class=\"alert alert-danger\">";
          echo "<strong>An error has occurred.</strong><br>" . $e -> getMessage();
          echo "</div>";
      }

But no matter how recent the token is, when the user submits the token the catch is called and the warning displayed. Even if the token was generated literally seconds ago, this happens.

Can someone please enlighten me as to what's wrong?


Source: (StackOverflow)

Dropbox file upload automatically using php

I'm playing with Dropbox API for PHP, and I would like know the correct way to upload files automatically without command line.

Now my process is:

  1. php -f upload.php
  2. Copy long url on browser
  3. Click allow button
  4. Copy the token
  5. paste the token on console and done.

My plan is do an automated backup of some JSON files on my Dropbox.

Is there other way to make that without console? and copying tokens and simple solution?

EDIT When I try to hardcode it, the output it´s ->

Fatal error: Uncaught exception 'Dropbox\Exception_BadRequest' with message 'HTTP status 400
{"error_description": "code has already been used", "error": "invalid_grant"}'

EDIT 2*

The access token output

dusIlAq36pkAAAAAAAAHQ6daX9hwt-3wUL240gUUjIOYrscX2OYOkCyj8ZghUgG2

I set it as

$authCode = 'dusIlAq36pkAAAABBBBBAAAHQ6daX9hwt-3wUL240gUUjIOYrscX2OYOkCyj8ZghUgG2';

Here Drop MSG

 ...Fatal error: Uncaught exception 'Dropbox\Exception_BadRequest' with message 'HTTP status 400
{"error_description": "code doesn't exist or has expired",

Source: (StackOverflow)

Call to undefined function readline()?

I am integrating Dropbox into my PHP based website. When i try to run the following code. i got this Fatal error: Call to undefined function readline() on the last line.

require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("app-info.json");

echo "<pre>";
print_r($appInfo);
echo "</pre>";

$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");

echo "<pre>";
print_r($webAuth);
echo "</pre>";

$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n<br>";
echo "2. Click \"Allow\" (you might have to log in first).\n<br>";
echo "3. Copy the authorization code.\n<br>";
$authCode = \trim(\readline("Enter the authorization code here: "));

I have come through different forum where people said it will work in Command line , But I don't understand how? Any idea ?


Source: (StackOverflow)

Mulitiple Files upload to Dropbox by PHP API

I was tried to upload files using Dropbox PHP Api . its worked perfectly . Is there any option in Dropbox api for multiple file uploads . or any asynchronous uploading concept is there in php ? . Currently i am using oauth2.0 for app signin .

 /**
 * Uploads a physical file from disk
 * Dropbox impose a 150MB limit to files uploaded via the API. If the file
 * exceeds this limit or does not exist, an Exception will be thrown
 * @param  string      $file      Absolute path to the file to be uploaded
 * @param  string|bool $filename  The destination filename of the uploaded file
 * @param  string      $path      Path to upload the file to, relative to root
 * @param  boolean     $overwrite Should the file be overwritten? (Default: true)
 * @return object      stdClass
 */
public function putFile($file, $filename = false, $path = '', $overwrite = true)
{
    if (file_exists($file)) {
        if (filesize($file) <= 157286400) {
            $call = 'files/' . $this->root . '/' . $this->encodePath($path);
            // If no filename is provided we'll use the original filename
            $filename = (is_string($filename)) ? $filename : basename($file);
            $params = array(
                'filename' => $filename,
                'file' => '@' . str_replace('\\', '/', $file) . ';filename=' . $filename,
                'overwrite' => (int) $overwrite,
            );

            return $this->fetch('POST', self::CONTENT_URL, $call, $params);

        }
        throw new Exception('File exceeds 150MB upload limit');
    }

    // Throw an Exception if the file does not exist
    throw new Exception('Local file ' . $file . ' does not exist');
}

This script i am using


Source: (StackOverflow)

$_FILES to a resource - Laravel 5 and Dropbox

Well, I've uploaded an app to Heroku, and I've discovered that I can't upload files to it. Then I started to use Dropbox as storage option, and I've done a few tests, of send and retrieve link, and all worked fine.

Now, the problem is to use the uploadFile() method on DropboxAdapter. He accepts an resource as the file, and I did'nt work well. I've done a few tests, and still no way. Here is what I am doing, if anyone could me point a solution, or a direction to this problem, please. :)

Here is my actual code for the update user (Update the user image, and get the link to the file).

        $input = $_FILES['picture'];
        $inputName = $input['name'];
        $image = imagecreatefromstring(file_get_contents($_FILES['picture']['tmp_name']));

        Storage::disk('dropbox')->putStream('/avatars/' . $inputName, $image);

        // $data = Storage::disk('dropbox')->getLink('/avatars/' . $inputName);


        return dd($image);

In some tests, using fopen() into a file on the disk, and doing the same process, I've noticed this:

This is when I've used fopen() on a file stored on the public folder

http://i.imgur.com/07ZiZD5.png

And this, when i've die(var_dump()) the $image that I've tried to create. (Which is a suggestion from this two links: PHP temporary file upload not valid Image resource, Dropbox uploading within script.

http://i.imgur.com/pSv6l1k.png

Any Idea?


Source: (StackOverflow)

Redirect loop and sessions issue in Dropbox SDK

I am trying to do some customization on a basic code to authenticate to dropbox. I want my application to authenticate the user to dropbox directly, no third authentication involved. So basically the only authentication I want to have is against Dropbox. Currently I am having two problems:

  1. The code I came with goes into a infinit redirect loop.
  2. I am receiving the following php error I think related to $_SESSION:

    [Mon May 25 12:45:40.651325 2015] [:error] [pid 6568] [client 127.0.0.1:48900] PHP Fatal error:  Uncaught exception 'Dropbox\\WebAuthException_Csrf' with message 'Expected '0_2rtH-FFcAqzX4JLKPVKw==', got 'zdmJEkNgto3lA7qAgGW2SQ=='.' in /var/www/php/oauth/vendor/dropbox/dropbox-sdk/lib/Dropbox/WebAuth.php:242\nStack trace:\n#0 /var/www/php/oauth/web/dropbox_finish.php(11): Dropbox\\WebAuth->finish(Array)\n#1 {main}\n  thrown in /var/www/php/oauth/vendor/dropbox/dropbox-sdk/lib/Dropbox/WebAuth.php on line 242
    

This is my code start.php:

session_start();
require_once __DIR__.'/../vendor/autoload.php';
$key = "fttwagu78r37ped";
$secret = "9s10lkjhrwpujbl";
$GLOBALS['app_name'] = "oauth-php/1.0";
$GLOBALS['redirectURI'] = "https://oauth.dev/dropbox_finish.php";
$GLOBALS['HomeURI'] = "https://oauth.dev";

$appInfo = new Dropbox\AppInfo($key, $secret);
$csrfTokenStore = new Dropbox\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
$webAuth = new Dropbox\WebAuth($appInfo, $GLOBALS['app_name'], $GLOBALS['redirectURI'], $csrfTokenStore);

$authURL = $webAuth->start();
header("Location: $authURL");

and this dropbox_finish.php:

require_once "../app/start.php";
try {
   list($accessToken, $userId, $urlState) = $webAuth->finish($_GET);
   assert($urlState === null);  // Since we didn't pass anything in start()
}
catch (dbx\WebAuthException_BadRequest $ex) {
   error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
   // Respond with an HTTP 400 and display error page...
}

Can anyone help me with this one?


Source: (StackOverflow)

Gaufrette and Dropbox adapter: Dropbox_Exception_Forbidden: Forbidden

I'm getting the error below when I'm running $filesystem->has('foo'). What am I doing wrong?

Dropbox_Exception_Forbidden: Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location. Invalid or missing signature


Source: (StackOverflow)

Google Doc and DropBox PHP api's

I want to add a list of all files from my google docs and from dropbox on my website(not a google site). The code of my website is mostly in PHP. I am unable to find a PHP guide for Google Docs list API and dropbox API. Any help is appreciated thanks in advance.


Source: (StackOverflow)

Getting lots of entries in delta API

I have an app where i am using delta API to keep up with user's metadata changes. I have a user for whom i am getting a lot of entries and cursor is keep on changing. It has been 2 days and still i am keep on getting new cursor, which has "has_more" as true. I have so far processed about 400,000 entries and only 17,000 entries were entries with metadata, all others were delete entries.

Is this a normal behavior?


Source: (StackOverflow)

Dropbox API: how to use the "path" value to display images

I'm using Dropbox Core API + PHP.

I'm dealing with

https://api.dropbox.com/1/search/dropbox/

It may be a silly question, but when i get back the json file, similar to

[
    {
        "size": "0 bytes",
        "rev": "35c1f029684fe",
        "thumb_exists": false,
        "bytes": 0,
        "modified": "Mon, 18 Jul 2011 20:13:43 +0000",
        "path": "/mypics/image1.jpg",
        "is_dir": false,
        "icon": "image1",
        "root": "dropbox",
        "mime_type": "jpg",
        "revision": 220191
    }
]

The path is something like "mypics/image1.jpg": but what's the absolute url? How can i display that image correctly in my domain?


Source: (StackOverflow)