How to get the file URL from Google drive in PHP?

143 Views Asked by At

I tried to use the Google Drive API quickstart.php and changed part of it to list the file URL. However it didn't work. Can anyone help me?

Here is my code, the last part of the code is to print name, id, and URL of the files.

<?php
/**
 * Copyright 2018 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// [START drive_quickstart]
require_once __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

use Google\Client;
use Google\Service\Drive;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Google\Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE,"https://www.googleapis.com/auth/drive.readonly");
    $client->setAuthConfig('credentials.json');
    $client->setRedirectUri('http://127.0.0.1/home/ubuntu/intern/quickstart.php');
    $client->setAccessType('offline');
    $client->setPrompt('consent');
    $client->setIncludeGrantedScopes(true);

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    try{


        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n", $authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));

                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                $client->setAccessToken($accessToken);

                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            }
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        }
    }
    catch(Exception $e) {
        // TODO(developer) - handle error appropriately
        echo 'Some error occured: '.$e->getMessage();
    }
    return $client;
}


// Get the API client and construct the drive object.
$client = getClient();
$drive = new Google\Service\Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
    'pageSize' => 10,
    'fields' => 'nextPageToken, files(id, name, webContentLink)'
);
$results = $drive->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
    print "No files found.\n";
} else {
    print "Files:\n";
    foreach ($results->getFiles() as $file) {
        printf("%s (%s)", $file->getName(), $file->getId());
        $webContentLink = $file->getWebContentLink();
        if (!empty($webContentLink)) {
            printf("Web Content Link: %s\n", $webContentLink);
        }
        else{
            echo"can't generate URL \n";
        }
    }
}
// [END drive_quickstart]

I expect there will exist the URL in my terminal, but it didn't.

enter image description here

1

There are 1 best solutions below

0
Tanaike On

Modification points:

  • In the current stage, the values of webContentLink return only when the mimeType is not a Google Docs file (Document, Spreadsheet, Slide, and so on) and folder. I guessed that from the length of your showing file ID, the reason for can't generate URL might be due to this.
  • If you want to show the view link, how about using webViewLink instead of webContentLink?
  • Or, if you want to use webContentLink, how about checking the mimeType of the file?

When these points are reflected in your script, how about the following modification?

Pattern 1:

In this pattern, webViewLink is used instead of webContentLink.

$client = getClient();
$drive = new Google\Service\Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
    'pageSize' => 10,
    'fields' => 'nextPageToken, files(id, name, webViewLink)'
);
$results = $drive->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
    print "No files found.\n";
} else {
    print "Files:\n";
    foreach ($results->getFiles() as $file) {
        printf("%s (%s)", $file->getName(), $file->getId());
        $webViewLink = $file->getWebViewLink();
        printf("Web View Link: %s\n", $webViewLink);
    }
}

Pattern 2:

In this pattern, webContentLink is used by checking the mimeType. If the mimeType is Google Docs file, webViewLink is used.

$client = getClient();
$drive = new Google\Service\Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
    'pageSize' => 10,
    'fields' => 'nextPageToken, files(id, name, webContentLink, mimeType, webViewLink)'
);
$results = $drive->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
    print "No files found.\n";
} else {
    print "Files:\n";
    foreach ($results->getFiles() as $file) {
        printf("%s (%s)", $file->getName(), $file->getId());
        if (false === strpos($file->getMimeType(), 'application/vnd.google-apps')) {
            $webContentLink = $file->getWebContentLink();
            printf("Web Content Link: %s\n", $webContentLink);
        } else {
            $webViewLink = $file->getWebViewLink();
            printf("Web View Link: %s\n", $webViewLink);
        }
    }
}

Note:

  • In the above scripts, if you want to use the shared link, please modify this script as follows.

    • From

      printf("Web View Link: %s\n", $webViewLink);
      
    • To

      printf("Web View Link: %s\n", str_replace('drivesdk', 'sharing', $webViewLink));
      
  • If you want to retrieve the URLs for exporting the files, when the mimeType is Google Docs file, how about using exportLinks?

Reference: