Home Ask Login Register

Developers Planet

Your answer is one click away!

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");

if (isset($_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();
    $data = file_get_contents('./uploads/'.$name);
    $createdFile = $service->files->insert($file, array(
          'data' => $data,
          'mimeType' => 'application/pdf',
          'uploadType' => 'multipart'


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


Leave an answer

Quote of the day: live life