Daman February 2016

Allow users to upload files to my google drive script

I have forms that can be filed by users and uploaded to my google drive. The following code accomplishes that task. However, it also asks permission from the user to access their drive, and uploads to the user's drive and not to my drive. I want this to upload directly to my Google drive.

How can I allow my script access to my drive? Can I use a kind of hard-coded tokens or access tokens?

$client = new Google_Client();
$client->setApplicationName("Drive API Quickstart");
$client->setDeveloperKey("xxxxxxxxxxxx");
$client->setRedirectUri("xxxxxxxx");
$client->setClientId('xxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType("online");
$client->setApprovalPrompt("auto");

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);  
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));

}

if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
    $authUrl = $client->createAuthUrl();
    print "<center><a class='login text-center btn btn-primary' href='$authUrl'>Connect with google to upload file!</a></center>";

    }  

    if (isset($_SESSION['token'])) {
    $service = new Google_Service_Drive($client);
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($name);
    $file->setDescription('Document');
    $file->setMimeType('application/pdf');
    $data = file_get_contents('./uploads/'.$name);
    $createdFile = $service->files->insert($file, array(
          'data' => $data,
          'mimeType' => 'application/pdf',
          'uploadType' => 'multipart'
        ));

Answers


adjuremods February 2016

You'll have to check out Service Accounts. Service Accounts are accounts that belong to the application rather than the user. It acts on the user's behalf to call the APIs so they're accounts aren't really involved.

This way, the uploaded file will go to the email set on the service account which you can control. Once done, you can set the Share settings of the Service Account to with your main account just like what this dev did.

Hope this helps!

Post Status

Asked in February 2016
Viewed 2,977 times
Voted 12
Answered 1 times

Search




Leave an answer