Jump to content
bc-vnt

Google Drive and PHP: how to integrate

Recommended Posts

What is Google Drive

Google Drive (GDrive or just) is the name of a platform based on Cloud Computing and made available by the group of Mountain View for storing and sharing content through the network.

The service, which provides basic free 5 Gb for allocation to all holders of a Google account, is equipped with features for synchronization thanks to which you can always have access to their documents, regardless of the device used, the operating system reference and their place of work.

Since Google Drive associated with the API (Application Programming Interface), developers will be able to create software based on different languages ??can interact with the content it manages.

This discussion will address the subject of how to create PHP applications for the handling of documents stored via that service.

Registering the activation and the API

The first step to creating an application that interacts with Google Drive, will be to register a project in API Google APIs console, this procedure will enter into communication with the programming interfaces available to available beyond the limits of anonymous access, to monitor the use of the API and to control access to them and to share the management API within a team.

Once authentication to your Google account, you can go to the page to create your projects, "Google apis", the user can then click on the Create button located inside the project box reproduced from the following:

create-project.png

The platform will offer a complete list of the available interfaces, each of them will be given the status information ("off" when inactive "on" when activated and "Request access ..." when it is necessary to make a specific request for access ), the maximum (Courtesy limit) of daily call allowed for the service and, if necessary, at a price for their use.

In this case, the API to be used will be those denominated Drive Drive SDK and API (one of the few not to provide a ceiling for the demands of interaction) that, by default, are disabled:

API-600x75.png

To activate the API you will need to click on the button associated with each item in the column named Status, the system will ask you to accept the terms of service to use interface, this is done they will be active:

attivazione-API-600x73.png

For an application to interact with APIs Mountain View, you will need these to be able to authenticate itself to the service through a procedure that will be described in the next section, but for now, suffice it to say the application created in this discussion will interact primarily with Drive API interface, Drive SDK is instead a toolkit that can be used by those wishing to integrate applications in Google Drive.

Authentication applications on Google Drive

Anonymous access to the Google API provides the ability to perform only a limited number of requests, for this reason, clicking on the "API access" the vertical menu on the left side of the API section of Google apis project, you will have the opportunity to accessing credentials usable to authenticate applications to the API; specifically, the system provides two different modes of authorization: the first is called Simple API access and involves the use of API keys allowing identification of a project when there is the need for access to user data.

SimpleAPIKey.png

The most advanced level of authentication takes its name of Authorized Access API, it is based on the OAuth protocol (specification 2.0) that allows you to interact with protected data virtual devices, called tokens, passed as parameters to the API provided by a service providers such as Google.

Using OAuth includes the generation of a unique identifier called a client ID that you can get by clicking on Create an OAuth 2.0 client ID ...

OAuthCreate.png

The system will make it possible to access a module that will require the establishment of Project Data (Branding Information), such as the name and logo associated with it, these parameters will be shown to the user whenever there is a request for access to their confidential information through the client ID:

Branding-600x394.png

Your entries, you can either click on Next and proceed to step actual generation of the client ID, the new module will allow you to define the type of application for the project and, in this case, should be checked the radio button associated with the Installed voice application and the procedure for the creation of Installed applications is pretty much the same compared to that for the "Web applications" but faster, you make sure that you select only the Other entry in the menu named Installed application type.

Without this, you can end the current phase using the Create button client ID:

CreateID2-600x418.png

At this point the project will have at his disposal an identifier that will be associated also a secret key (secret Client) for identifying a URI and default for the redirection of calls to the service:

ClientIDInfo2.png

This data will allow to authorize the project when prompted to interact with the API provided by Service Provider.

Interaction through Google API PHP Client Library

Once you have the necessary credentials to interact with the service API, you can go to step on the creation of the application itself, to do this PHP developers will have a special library called Google API PHP Client which can be downloaded free and used freely as released under an Open Source license.

Once you download the library, it can be used to request that Google Drive to allow access by the generated project functionality for viewing and managing content stored in the cloud platform and for this purpose you can run a script along the lines of the following:

<?php
// inclusione delle librerie del client
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

// istanza dell'oggetto di classe relativo al client
$drive = new Google_Client();

/* credenziali e parametri per l'autenticazione */
# identificatore, o client ID, associato al progetto
$drive->setClientId('xxxxxxxxxxx.apps.googleusercontent.com');

# chiave segreta associata al progetto
$drive->setClientSecret('xxxxxxxxxxxxxxxxW5sOe');

# URI per la redirezione delle richieste
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');

# percorso alla risorsa di Google Drive alla quale è indirizzata la richiesta
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));

// istanza dell'oggetto di classe relativo al servizio
$gdrive = new Google_DriveService($drive);

// creazione dell'URL per l'autenticazione
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));

// trasferimento del token di accesso per l'utorizzazione
$token = $drive->authenticate($authorizationCode);
?>

In practice, the snippet proposed service to send a connection request and, to do this, use as parameters the client ID and the secret key previously obtained that must be passed as arguments to methods respectively setClientId () and setClientSecret (); also, will be necessary to go to method setRedirectUri () the redirect URI default supplied automatically by the service at the time of generation of the client ID and, to setScopes method (), the service URL to which the access request will be performed which, in specific case, is "https://www.googleapis.com/auth/drive".

Running the script, the browser client should undergo a redirect to a page for the request for authorization as follows:

AutorizzazioneProgetto-600x224.png

At this point, you will need to continue to click on the button "Allow access" system, respecting the mechanics of OAuth based on the exchange of tokens between application and Provider, will provide a code that can be used to authorize the application at the time interaction with the API.

codicedacopiare.png

Once you have the code, you will not need to ask for it again to interact with content in Google Drive, but to do this the benchmark application must be able to communicate it to the service when it is required for authentication purposes .

Upload files to Google Drive from a PHP application

A practical application in terms of the interaction of a PHP script with programming interfaces to Google Drive could be the inclusion of a file in the folder for your account.

To do this you can use the library again Google API PHP Client by creating a part similar to that previously proposed:

<?php

// inclusione delle librerie del client
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

// istanza dell'oggetto di classe relativo al client
$drive = new Google_Client();

// credenziali per l'autenticazione
$drive->setClientId(' xxxxxxxxxxx.apps.googleusercontent.com');
$drive->setClientSecret('xxxxxxxxxxxxxxxxW5sOe');
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));

// istanza dell'oggetto di classe relativo al servizio
$gdrive = new Google_DriveService($drive);

// salvataggio del token in una variabile
$_GET['code']= '4/xxxxxNIVCxxxxxx1xAO0bxMe.kjgvxxxxxl05txxxxxxdAI';

// memorizzazione del token in un file
file_put_contents('token.json', $drive->authenticate());

// lettura delle informazioni contenute nel file
$drive->setAccessToken(file_get_contents('token.json'));

// istanza dell'oggetto di classe relativo al file per i test
$doc = new Google_DriveFile();

// intestazioni per il file di test
$doc->setTitle('Test Progetto Drive');
$doc->setDescription('Documento di prova');
$doc->setMimeType('text/plain');

// lettura del contenuto del file e restituzione sotto forma di stringa
$content = file_get_contents('progettodrive.txt');

// generazione del file per il test
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));

// stampa del risultato
print_r($output);

?>

The first part of the code provides for the inclusion of library files and authentication credentials associated with your project, but in this case, the code provided at the time of the access request will be passed as a parameter to a variable of method in so that it can be written using the function file_put_contents () within a file ("token.json"), then it will be readable through another function of PHP, file_get_contents (), so that the application is authorized.

The next step will involve writing the headers of a simple text file which you can define:

  • a title by the method setTitle ();
  • a brief description, by the method setDescription ();
  • the MIME type (in this case "text / plain") by the method setMimeType ().

In the example, the file to upload (simply called progettodrive.txt), you will be in the same path to the file containing the code and, within it, can be written any string (in this case "Test carried out successfully! ") to check the place then move to folder of Google Drive.

The insert () method will be responsible for writing the header file and to upload required, passing the variable as populated ("$ output") to print_r () function, you can view the information about the process of editing and downloading the file.

Once the PHP application proposal, within the folder Google Drive should be a new file with the title of the string passed to the method setTitle () ("Test Drive Project" in the example):

FileSalvato-600x268.png

Opening the new file should be viewable within it the same string written in the source text file, this showing dell'avvenuto upload:

AperturaFile.png

The outcome of the last test performed demonstrate irrefutably the overcoming of the phases of the application authentication service and communication with its API.

Sursa :

http://www.html.it/articoli/google-drive-e-php-come-integrarli/

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...