ccc

Google API: Subir ficheros a Google Drive desde PHP

a) Descargar https://github.com/numsu/google-drive-sdk-api-php-insert-file-parent-example

b) Ir a https://console.developers.google.com para habilitar la API de Google Drive

c) Ir a Biblioteca -> Buscar "Google Drive API" y habilitar esa API.

d) Ir a Credenciales -> Crear un nuevo IDs de cliente de OAuth 2.0

Con esto obtendrás:
ID de cliente
Secreto de cliente
url de Retorno: la ruta del fileUpload.php de lo previamente descargado, por ejemplo http://www.midominio.com/googleDrive/fileUpload.php

e) Editar el fichero functions.php con los datos proporcionados, por ej:
$CLIENT_ID = "261115921671-4l0XXXia7pi1bkluv54qhg785un4jqvd.apps.googleusercontent.com";
$CLIENT_SECRET = "UB-L_EW3D-xnXXXeR1cIaOUY";
$REDIRECT_URI = "http://www.midominio.com/googleDrive/fileUpload.php";

f) Editar el fichero index.php con dichos datos:
$authUrl = getAuthorizationUrl("261115921671-4l0XXXia7pi1bkluv54qhg785un4jqvd.apps.googleusercontent.com", "UB-L_EW3D-xnXXXeR1cIaOUY");

g) Ejecutar en el servidor ese index.

--------------------------------------------------------------------

Importante: Si lo ejecutas varias veces puede dar algún error, para que no de hay que desloguearse de tu cuenta de google y volver a ejecutarlo.

Si quisieramos listar todos los ficheros subidos al Drive (por motivos de seguridad solo permite listar aquellos ficheros que has subido con tu cuenta) sería por ejemplo en el fileUpload.php añadir:
<h3><a href="listarFicheros.php">Listar ficheros del Drive</a></h3>

Y luego listarFicheros.php:
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Oauth2.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';
session_start();

header('Content-Type: text/html; charset=utf-8');


$credentials = $_COOKIE["credentials"];

$json = json_decode(file_get_contents("./conf/GoogleClientId.json"), true);
$CLIENT_ID = $json['web']['client_id'];
$CLIENT_SECRET = $json['web']['client_secret'];
$REDIRECT_URI = $json['web']['redirect_uris'][0];


$client = new Google_Client();
$client->setClientId($CLIENT_ID);
$client->setClientSecret($CLIENT_SECRET);
$client->setRedirectUri($REDIRECT_URI);
$client->addScope(
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.appfolder");


$client->setAccessToken($credentials);
$service = new Google_Service_Drive($client);
$files = $service->files->listFiles();


foreach ($files['items'] as $item) { ?>
<a target="_blank" href="<?=$item['alternateLink'];?>"> <?=$item['title'];?> </a>
<br>
<?php
}

Más fácil, subir al Drive todo lo que haya en una carpeta local de tu ordenador:
https://github.com/leandrosiegar/google_drive_upload_from_folder

Ojo: En algunas versiones de PHP (como la 5.3) no funciona el mime_content_type

No hay comentarios:

Publicar un comentario