Powered By Blogger

Wednesday, April 27, 2016

Steps for Uploading Document in GDrive using PHP

Steps for Uploading Document in GDrive using PHP


     a) Create New project in your google account (https://console.developers.google.com)

     b) Generate the API key, Client Id, Client Secret key and set the redirect URL.

      c) Enable the following API

           i) Google+ API
           ii ) Google Drive API

     d) Set the Key value in the variables

$client_id="317376393022-bd7……………………….";
   $client_secret="CygAQWlG0_……………………..";
   $url="Redirect URI";

      e) Include the API Files for Uploading

   include_once APPPATH . "libraries/google-api-php-client/src/Google_Client.php";
   include_once APPPATH . "libraries/google-api-php-client/src/contrib/Google_DriveService.php";

      f) Setting the Key values to the variable

   $client = new Google_Client();       // Create object for Google_client class
   $client->setClientId($client_id);
   $client->setClientSecret($client_secret);
   $client->setRedirectUri($url);
   $client->setScopes(array('https://www.googleapis.com/auth/drive'));

      g) Check whether the code Request variable available else call the authenticate function for the getting the access token

   if (isset($_GET['code'])) {
   echo  $_SESSION['accessToken'] = $client->authenticate($_GET['code']);
   header('location:'.$url);exit;
   } elseif (!isset($_SESSION['accessToken'])) {
   echo $client->authenticate();
   }



  
  
   $client->setAccessToken($_SESSION['accessToken']);   // Setting the acces tokent to client object


   $service = new Google_DriveService($client);    // Create Object for Driveservice
   $finfo = finfo_open(FILEINFO_MIME_TYPE);
   $file = new Google_DriveFile();                         // Create Object for Drive file
  
     

                  h) Setting the file value to Drivefile object ($file)

        $file_path = 'assets/test.xlsx';       // File Path
        $mime_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';          // Mime type
        $file->setTitle('sathiya file');
        $file->setDescription('This is a '.$mime_type.' document');
        $file->setMimeType($mime_type);

       i) Using the Driveservice object ($service) insert the file to gdrive

        $output=$service->files->insert(
            $file,                                                                 // Pass the file object as the parameter
            array(
                'data' => file_get_contents($file_path), // File path
                'mimeType' => $mime_type,                 // Mime Type
                'convert' => true,                                   // This key is set when we convert the file to some other object
            )

        );

No comments:

Post a Comment