Use PHP to access Dropbox_PHP tutorial

Source: Internet
Author: User
Tags oauth php session
Use PHP to access Dropbox. In this article, we will explore accessing files in the Dropbox account by building a simple DropboxAPI for the client. The client will perform some basic operations, such as authentication and listing files. in this article, we will discuss how to access files in the Dropbox account by building a simple Dropbox API for the client. The client will perform some basic operations, such as authentication, listing files, uploading and downloading files.
For short and readable articles, I will keep the code to a minimum, instead of providing complete code on your PHPMaster GitHub. To run the code, you need to support curl, apparently a PHP Dropbox account.
Your starting point should be any development center related to development and Dropbox, where you can find its basic concepts and API reference for best practices. You can also download the official SDK, which is listed in languages not supported by PHP. There is also a link to third-party php sdk GitHub.
Our customers will be structured more like the official Python client, but I have noticed that, especially for part of OAuth, some ideas and code from the above PHP SDK ,. We will have a DropboxSession object and a DropboxClient object. First, take care of the most difficult part: getting and managing access creden。 from Dropbox. The client object, and then the session object will be used to execute API calls and obtain data. The following session object is the DropboxRESTClient object used to execute HTTP calls using cURL.
Tell Dropbox about your application
First, we need to register our application to obtain a unique API key pair with Dropbox. We need these keys to "import" our applications and requirements for authorization.
Log on to the development center, follow the "MyApps" link, and select "create an application ". Dropbox will ask your name, description, for your application and access type.

The access type parameter specifies that your application can read and write files. The recommended value is "application folder". a sandbox is created for the user's home in the directory. Select the "full Dropbox" application to set the user's entire Dropbox.
Once your application is created, there is an option page where you can edit its details and find its access creden.

The newly created application is in the "Development Status ". This allows us to start development immediately and allow up to five other users to test it. When the application is ready for release, we can apply for production status and the Dropbox team will review it to ensure it complies with its terms and conditions and brand guidelines.
Encoding application
I set my code in a sub-directory of my local Apache so that it accesses http: // localhost/mydropbox at URL. The directory structure is:

Bootstrap. php file, execute application startup, will be in each front-end file, so let's start to discuss ,.
I initialize a global configuration as an empty array variable and specify some configuration values. The first three Dropbox related access keys and keys, and access types from the details page of your application. Then, I define some other useful settings: the application's base root path, save some data, and a php file path will contain the application's access token.
This access token file does not exist in the beginning; it creates creden。 provided by the authorize. php page and full Dropbox. This will be a standard PHP file. if it exists, it will be included in this script. The content of the token file will be similar:
$ Access_token = array (
"Oauth_token_secret" => "abcdefghilmnopqr ",
"Oauth_token" => "stuvwxyzabcdefgh ",
"Uid" = & gt; "1234567"
Oauth_token and oauth_token_secret access creden。. UID is the unique ID of the user.
In the next section, I set the PHP error behavior in the boot file and run some request checks. to run the application, the data directory must exist and can be written with auth. php files must be writable if they exist. This will ensure that the application can do its work freely.
Finally, I include our library, PHP session initialization, set an empty $ access_token (will be filled in later), and if it exists, including the auth. PHP file.
Each front-end script runs a major attempt/capture block. Before digging the library code, we need to understand the traffic first, so I will start with the authorization cycle.

When we run our application for the first time, the index. php file will be real under the following conditions:
1 2 if (! Isset ($ access_token )){
3 header ("Location: authorize. php ");
4 exit;
The access token is empty, so I will redirect the user to the authorize. php page and manage the authorization process.
After the boot phase, I perform another existing token check. This will ensure that this script runs only when we don't have a token. To avoid infinite redirection loops, the auth. php file is mainly caught by the deleted script block if the returned error code is 401 (invalid token ).
The first thing I do in every script is to create a new DropboxSession object with our API key. When we call the script directly, the first condition is false, and other blocks are executed. The session object is connected to the Dropbox and requires a temporary token. Token, and then parsed into an array to store it in the next phase of the variable $ _ SESSION.
We create a URL to authorize the use of this token. The user should redirect or prompt the access url where he will decide whether to allow or deny access to his data.
An authorized URL can contain an optional parameter and return a URL. I only use the URL of the current script, so if the user authorizes him to redirect to our script application, the oauth_token and UID of the time used to query the value passed by the string. Now the first condition is evaluated to be true, so we can go and require a permanent access token.
The dollar token requires the array of this newly built oauth_token with the previous oauth_token_secret, which is then passed to the obtainAccessToken () method. If successful, we have our permanent (until UNDO) access token. This must be stored somewhere. the obvious choice is a database, but in this example, we use the local var_export () function as a valid PHP code and write it into our auth. php file. Then redirect the user to the index page, which is the simplest script.
When we start to try/capture to prevent a new DropboxSession object from being created, this time $ access_token will be used as the fourth parameter. This object is used to create a DropboxClient object. These two steps share all other scripts.
The public methods of the client are mapped to the corresponding Dropbox API call. The AccountInfo () method I called returns an array containing the user's details: Unique ID, name, email, quota information and promotion links (more details of the official document ).
Behind the Scenes: REST and session objects
Now we have an overview of the surface stream. let's see what happened under the hood. our Dropbox Library is included in the lib/Dropbox Directory, including three types.
Static object

Our library is a REST client (see LIB/safe deposit box/rest. php ). This class is simple packaging for curl. It executes an HTTP call and returns the output in raw material or encoding format, or throws an exception in case of an error.
The construction check cURL is installed on the system, or an exception is thrown. Then, it tries to initialize the internal curl and handler dollar curlDefaults settings. The handler is not set in the destructor.
() Error, and the errno (), () method is self-evident. Then, we have a series of practical methods to get the (), Post (), and put () method for simple packaging, all the main requirements () method, which actually works.
First, we set the URL to get the HTTP method and required parameters, additional headers and POST (if any ). Pass the parameters of the GET and PUT methods along the URL caller method.
Before calling, we need to tell the whole content of the curl search, including the HTTP header (set the option CURLOPT_HEADER), because some API methods (of course file_get () put their information, in the header.
The result of the curl request being executed and stored to curl_exec () is the response and metadata of the variable is filled with curl_info () related to the execution details. If the proposed method is used, we also have to close the input file handle.
The meta-response content and metadata, the analysis results, and the HTTP headers separated from the body. By default, the body returns JSON decoding. The original parameter except for non-USD is set to true.
There was an error check before what happened. The Dropbox API uses HTTP error code error notification. If the status code is greater than 400, an error or error message is stored in the body. I extract this message and throw an exception. If no error HTTP header is returned, the returned array contains the status code, header, and body.
Session object

The basic REST client of DropboxSession object extension is used to fill our needs:
Traffic for initial authentication/authorization,
Including obtaining verification data for each REST request in the future.
Construct simple initiazlizes internal variables. Another simple method is the temporary token authorization URL created by buildAuthorizeURL. The most important method of a class is:
ObtainRequestToken ()-requests a temporary OAuth access token.
ObtainAccessToken ()-the access token of the application that requires permanent OAuth.
Get ()-execute other calls, including all necessary authentication and signature parameters.
These three methods have similar flows. First, they establish the basic target URL and enter the params dollar, and send it with the required associated array oauth _ * key/value. Each API call must provide a timestamp and a unique random hash, the $ nonce parameter.
Then, use the HTTP method name, URL, and parameter to generate a signature. It then queues the dollar params array using the oauth_signature key. The URL is part of the body that is far fetched from the given HTTP method and response returned. For GET and PUT methods, the generated query string is appended to the local http_build_query () function used by the URL.
The obtainRequestToken and obtainAccessToken () are almost the same: first, do not use the token and a get http method call. The second method, known as a post http method, must include the token obtained with the previous call. This flag is then used to call part of the signature key with all of the following APIs.
The () method is used to execute some additional tasks. First, it requires an array named $ ARGS and any additional parameters required by a specific API, such as the resource list or the path for uploading/downloading files. These parameters are combined with the USD params array to generate a signature. The only exception is to use the PUT method to upload a file, extract and save parameters in the input file, and use the PUT method later. A switch statement is used to tell the correct HTTP method to call.
DropboxSession class two practical methods, encodeParams () and getSignature (), in the above main method call encodeParams () prepare the request parameters for signature, while getSignature () generate the signature required to call 1 OAuth in a given API.
Last DropboxClient object
The DropboxClient object is our high-level interface and Dropbox. It exposes the public API method, uses the mid-stage horizontal DropboxSession, the object executes the API call, and returns a processing output call script. In this article, I have implemented a set of limited methods:
AccountInfo ()-Get the details of the user in the current Dropbox.
Metadata ()-gets information about Dropbox objects (files or folders) and retrieves a list of folder objects.
GETFILE ()-Download the file and its metadata, and save it to the disk selectively.
PUTFILE ()-local file upload to the remote Dropbox path.
The URL of the session object and basic API is stored as internal variables and constructor initialization.
All methods follow the same method more or less, so I want to point out the difference. The root path of the Dropbox of each call must be taken into account in advance. The root path depends on the access type of the application. it can be a "safe deposit box" if the application has full access or a "sandbox" if the application has limited access. If this value does not match the remote settings of the application, an error is returned.
The common steps for each method are:
Check and prepare the parameter list.
Execute an HTTP call.
Parse and return a response.
The AccountInfo () method of is the simplest way to call a URL without parameters and return an Associated array of the response.
List. php file metadata () method to obtain and display the contents of the Directory. The only required parameter is the path of the file or directory to be checked, but it allows us to specify all other parameters called by the corresponding API. If the $ PATH parameter is a file, the returned array contains metadata. If it is a folder, the content item contains its file list, except that the non-dollar list parameter is false. We can limit the content size to the $ fileLimit parameter (max. 25000). we can ask a specific file or folder (For more information, see API reference) for revision.
It is important to note that the Dropbox API returns the hash value for each call. If we want to list the folder content and provide a hash parameter to change our method from the last call, the API checks whether the output is made. If not, it returns a 301 status code (cannot be modified ). The Dropbox team recommends caching results and optimizing performance by using these folder list values.
The GETFILE () method is used to retrieve the files stored in the user's Dropbox. When the entire file content is returned for a successful call, the metadata of X-Dropbox stored in the custom HTTP header is used as a JSON string. The returned value of this method is an associated array that contains the name, MIME type, metadata, and content. In addition, I have added the $ outfile parameter to directly save the file on the disk.
The download. php file shows a demo of this operation method. In this example, the downloaded file is saved directly to the data directory of the application, and part of the response content is cleared.
PUTFILE () method, from our local storage to the user's Dropbox file upload using the put http method, this is the Dropbox team, rather than the first choice for publishing. This method checks whether the local file exists and does not exceed the limit of 150 mb api.
Parameters that support this method, in addition to the source file path, target folder, an optional alternative name and overwrite options. If a remote file is stored, the uploaded file is an incremental digital name (for example, test.txt test (1 ). TXT ). The API also allows an optional parent_rev parameter to manage modifications, but I decided to ignore it to make things easier.
This is only a small part of the Dropbox API, but it can be used as a starting point to develop your own applications. For me, it is also a good opportunity to play with OAuth. It can be improved and expanded at any time, along with this article to meet your needs, and as always: Happy coding code!

Author: newcnzz

Ingress API. The client will perform some basic operations, such as authentication, listing files ,...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.