Access dropbox_php Tutorials with PHP

Source: Internet
Author: User
Tags oauth php session
In this article, we'll explore the Dropbox API for accessing files in a Dropbox account by building a simple client. The client will perform some basic operations such as certification, listing files, uploading and downloading files.
Keeping short-term and readable articles, I will keep the code to a minimum, rather than referring you to the full code on Phpmaster GitHub. To run the code you need to be supported with curl, apparently a PHP dropbox account.
Your starting point should be any development center with Dropbox Dropbox, where you can find its basic concepts and API reference for best practices. You can also download the official SDK, but PHP is not supported by the language listed. There is also a link to a third-party PHP SDK on GitHub.
Our customers will structure more like the official Python client, but I have noticed, especially on the part of OAuth, some ideas and code from the PHP SDK above. We will have a Dropboxsession object and a Dropboxclient object. Take care of the most difficult part first: Get and manage access credentials from Dropbox. The client object then uses the session object to execute the API call and fetch the data. The following session object is a Dropboxrestclient object that performs an HTTP call using Curl.
Tell Dropbox about your app
First, we need to register our app to get a unique API key pair with Dropbox. We need these keys to "bring in" our apps and ask for authorization.
Sign in to the Dev Center and follow the "MyApps" link, then select "Create an Application". Dropbox will ask you for the name, description, and type of access for your application.

The access type parameter specifies that your application will be able to read and write to the file. The recommended value is "Application Folder", in the directory within the user's home, will create a sandbox. Select the "Full Dropbox" app to be the user's entire Dropbox.
Once your application is created, there will be an options page where you can edit its details and find its access credentials.


The newly created app is in the "Development state". This allows us to start development immediately and allow up to 5 other users to test it. When the application is ready to be released, we can apply for production status and the Dropbox team will review to ensure that it complies with its terms and conditions and branding guidelines.
Coded applications
I put my code in a subdirectory of my local Apache so that it is accessed in URL http://localhost/mydropbox. The directory structure is:


The bootstrap.php file, which executes the application startup, will be in each front-end file, so let's start the discussion.
I initialize a global configuration as an empty array variable, and then specify some configuration values. The top three Dropbox related access keys, keys, and access types from your app's details page. Then, I define some other useful settings: the path to the application's Keegan, the storage of some data, and the path to a PHP file that will contain the application's access token.
This access token file does not exist in the beginning of the file; It creates the credentials provided by the authorize.php page and filled with Dropbox. This will be a standard PHP file, if present, will be included after this script. The contents of the token file will resemble the following:
$access _token = Array (
"Oauth_token_secret" = "ABCDEFGHILMNOPQR",
"Oauth_token" = "stuvwxyzabcdefgh",
"UID" = "1234567"
);
Oauth_token and Oauth_token_secret access credentials, UID is the user's unique ID.
I set PHP's error behavior in the next section of the boot file and perform some requirements checks; In order to run the application The data directory must exist and the writable auth.php file must be writable if it exists. This ensures that the application is free to complete its work.
Finally, I included our library, PHP session initialization, set a null dollar Access_token (will be filled in later), and, if it exists, include the auth.php file.
Each front-end script will run inside a primary try/catch block. Before digging the library code, we first need to understand the traffic, so I'll start with the authorization cycle.
Authorized

The first time you run our application, the index.php file under the following conditions will be true:
1 2 if (!isset ($access _token)) {
3 Header ("Location:authorize.php");
4 exit;
5}
The access token is empty, so I redirect the user to the Authorize.php page, which manages the authorization process.
After the boot phase, I do another existing token check. This will ensure that this script runs only if we do not have a token. In order to avoid an infinite redirect loop, the auth.php file is removed from the main catch of the script block if the error code returned 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 the other blocks are executed. The session object connects to Dropbox and requires a temporary token. The token is then parsed into an array to store the next stage in the variable $ _session.
We establish a URL that authorizes the use of this token. The user should redirect or prompt for access to the URL, where he will decide whether to allow or deny access to his data.
The authorization URL can contain an optional parameter that returns a URL. I just pass the URL of the current script, so if the user authorizes him to redirect the application to our script, this uses the value of the time of the Oauth_token and UID query string. Now the first condition evaluates real, so we can go and ask for a permanent access token.
The dollar token for this requirement array is the newly built Oauth_token with the previous Oauth_token_secret, which is then passed to the Obtainaccesstoken () method. In the case of success, we have our permanent (until revoked) access token. This must be stored somewhere, the obvious choice is a database, but in this case we will export as valid PHP code using the local Var_export () function and it is written in our auth.php file. Then redirect the user to the index page, which is the simplest script.
Before we begin to try/Catch a new Dropboxsession object that is created, this $ access_token is permanently used as the fourth parameter. This object is used to create the Dropboxclient object. These two steps are common to all other scripts.
The client's public method maps to the appropriate Dropbox API call. I called the AccountInfo () method, returning an array containing the user's details: A unique ID, name, email, quota information and referral link (referring to more details of the official document).
Behind the scenes: Rest and Session objects
Now that we have an overview of the surface flow, let's see what happens under the hood, our Dropbox library is included in the Lib/dropbox directory, including the three categories.
A stationary object

The lowest level of class, our library is the rest client (see LIB/Safe deposit box/rest.php). This class is a simple wrapper for curl. It executes an HTTP call and returns the output in raw or encoded format, or throws an exception in the case of an error.
The construct checks that curl is installed on the system, or throws an exception. Then, it tries to initialize the internal curl with the $ curldefaults setting of the handler. The handler is not set within the destructor.
() error, and the errno (), () method is self-explanatory. Then we have a series of practical methods to get (), post () and put () methods for simple packaging, all of the main requirements () methods, and it's actually working.
First, we set the URL to get the HTTP method and the required parameters, additional headers and post (if any). Along the URL caller method is passed for the get and put method parameters.
Before making the call, we need to tell curl to retrieve the entire contents, including the HTTP header (set option Curlopt_header), because some API methods (of course file_get ()) put their information in the header.
The curly request is executed to store the result for curl_exec () and the meta-information variable is filled by the curl_info () about the execution details. If the proposed method, we will also have to close the input file handle.
Meta-response to the content and meta-information we analyze the results from and separate the HTTP headers from the body. By default, the body returns the JSON decoding unless the original parameter of the dollar is set to true.
What's going on before there's a bug check. The Dropbox API uses HTTP error code error notification. If the status code is greater than 400, then an error and error message is stored in the body of the content. I extract this message and throw an exception. If there is no error in the HTTP header resolution, the returned array contains the status code, head and body.
Session Object

The Dropboxsession object extends the basic rest client to fill our needs:
Perform initial authentication/authorization of traffic,
Include the validation data for each rest request at a later time.
Constructs a simple initiazlizes internal variable. Another easy way is to create a temporary token authorization URL buildauthorizeurl (). The most important methods of the class are:
Obtainrequesttoken ()-Request a temporary OAuth access token.
Obtainaccesstoken ()-An access token for an application that requires permanent oauth.
Take ()-perform the rest of the call, including all necessary authentication and signature parameters.
These three methods also have similar flows. First, they set the basic target URL and fill in the params dollar, with the required associative array oauth_ * key/value to send. Each API call must provide a timestamp and a unique randomly generated hash of the dollar's nonce parameters.
The signature is then generated using the name, URL, and parameters of the HTTP method. It then queues the params array of dollars using the Oauth_signature key. The URL is forced with the given HTTP method and returns a part of the body of the response. For the 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 identical: one is to not use tokens and a Get HTTP method call. The second one that is called a post HTTP method must include a token obtained with the previous call. This token is then used as part of the signing key for all of the following API calls.
Take the () method to perform some additional tasks. First, it requires an array named Args with any additional parameters required by the specific API, such as the resource list or the path to the upload/download file. These parameters are combined with the params array of the dollar before the signature is generated. The only exception is to use the Put method to upload the file, input the parameters in the file, extract and save for later. A switch statement is used to tell the correct HTTP method to invoke.
The Dropboxsession class has two practical methods, Encodeparams () and Getsignature (), in which the Main method called Encodeparams () prepares the requested parameters for signature, The Getsignature () generates a request signature for 1 OAuth in a given API call.
Last Dropboxclient Object
The Dropboxclient object is our high-level interface with Dropbox. It exposes the method of the public API, uses the medium level dropboxsession, the object executes the API call, and returns a processing output call script. In this article, I have implemented a limited set of methods:
AccountInfo ()-Gets the details of the current Dropbox user.
Metadata ()-Gets information about the Dropbox object (file or folder) and retrieves a list of the contents of the Folder object.
GETFILE ()-Download the file and its metadata, and optionally save it to disk.
Putfile ()-The local file is uploaded to the remote Dropbox path.
The URL store for the session object and the base API is initialized for internal variables and constructors.
All methods follow the same method more or less, so I want to point out the difference. All path-handling methods must be pre-considered for each call to the Dropbox root path. Depending on the root path of the application's access type, it can be a "safe deposit box" If the application has full access or "sandbox" if the application has limited access. If this value does not match the remote setting of the application, an error is returned.
The common steps that each method performs are:
Examine and prepare the parameter list.
Executes an HTTP call.
Resolves and returns a response.
The AccountInfo () method is the simplest to call a URL without parameters and returns an associative array of responses.
list.php the file metadata () method to get and display the contents of the directory. The only parameter required is the path to the checked file or directory, but it allows us to specify all the other parameters for the corresponding API call. If the $ path parameter is a file, the returned array contains the metadata. If it is a folder, the content item contains a list of its files unless the dollar list parameter is false. We can limit the size of the content with the $ filelimit parameter (up to a maximum of 25000), we can ask a specific file or folder (for more information, see API Reference) revisions.
It is important to note that the Dropbox API returns a hash value for each call. If we want to list the contents of the folder and provide a hash parameter since the last call to change our method, the API check is output. If not, it returns a 301 status code (cannot be modified). The Dropbox team recommends caching the results and relying on these folder list values to optimize performance.
The GETFILE () method is used to retrieve files stored in the user's Dropbox. The entire file content is returned as a JSON string with the x-dropbox metadata stored in the custom HTTP header, which is called the success case. The return value of this method is an associative array that contains the name, MIME type, metadata, and content. Additionally, I have added the parameters in $ outfile directly to the files that are saved on the disk.
The download.php file shows a demonstration of this method of operation. In this example, the downloaded file is saved directly to the application's data directory, and the response is emptied of some content.
The Putfile () method, uploaded from our local store to the user's Dropbox file, uses the put HTTP method, which is the Dropbox team and not the preferred publication. This method checks for local files that exist and does not exceed the 150MB API limit before any other common actions.
Parameters that support this method, in addition to the source file path, destination folder, an optional alternative name and overwrite options. If this last option is false and there is a remote file, the uploaded file is named for a progressive number (for example, a test that becomes test.txt (1). TXT). The API also allows an optional Parent_rev parameter to manage the changes, but in order to make things simple I decided to ignore it.
Summarize
This is just a small part of the Dropbox API, but it can be as a starting point to develop your own applications enough. For me, it's also a good opportunity to play with OAuth. Be ready to improve and expand, along with this article to meet your needs, and as always: Happy coding Code!

Author: newcnzz

http://www.bkjia.com/PHPjc/478017.html www.bkjia.com true http://www.bkjia.com/PHPjc/478017.html techarticle In this article, we'll explore the Dropbox API for accessing files in a Dropbox account by building a simple client. The client will perform some basic operations, such as certification, 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: info-contact@alibabacloud.com 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.