How to retrieve shareable public URL from Google Drive API using PHP

I’m working with PHP and the Google Drive API to upload documents to a shared folder. The upload process works fine, but I’m struggling to extract the proper public sharing URL that I can use on my website.

$uploadResponse = Array
(
    ['resourceId'] => 'file_1A2B3C4D5E6F7G8H9I0J1K2L3M4N5O6P7Q8R9S0T1U2V3W4X5Y6Z'
    ['createdDate'] => '2023-10-15T14:22:35.789Z'
    ['modifiedDate'] => '2023-10-15T14:22:35.789Z'
    ['mimeType'] => 'application/pdf'
    ['originalFilename'] => 'report_document.pdf'
    ['downloadUrl'] => 'https://drive.google.com/uc?id=1A2B3C4D5E6F7G8H9I0J1K2L3M4N5O6P7Q8R9S0T1U2V3W4X5Y6Z&export=download'
    ['alternateLink'] => 'https://drive.google.com/file/d/1A2B3C4D5E6F7G8H9I0J1K2L3M4N5O6P7Q8R9S0T1U2V3W4X5Y6Z/view'
)

The response contains various URLs but none of them work as a direct public link for embedding on my site. I need to get a URL that allows public access without requiring authentication. What’s the correct way to obtain this shareable link through the API?

Hit this same problem last month. Google changed their API - the upload response doesn’t give you the shareable link anymore. After you set permissions with permissions->create, make another call to grab the updated file metadata. That’ll have the webViewLink field you need. Try $updatedFile = $driveService->files->get($fileId, array('fields' => 'webViewLink')); - that should do it. You want webViewLink for public sharing, not alternateLink or downloadUrl from the upload. Spent hours trying to build URLs manually before I figured this out.

you’re missing the permissions step entirely. after uploading, you need to change the sharing settings or the file stays private. use $service->files->update($fileId, $file, ['addParents' => $parentId]) and enable sharing. the alternatelink will work once you set the permissions right.

The URLs from your upload response aren’t publicly accessible by default. You need to set file permissions after uploading. Here’s how to grant public read access using the Drive API: $permission = new Google_Service_Drive_Permission(); $permission->setRole(‘reader’); $permission->setType(‘anyone’); $driveService->permissions->create($fileId, $permission); Once that’s done, build your public URL with the file ID: https://drive.google.com/file/d/{FILE_ID}/view?usp=sharing. For embedding or previews, use: https://drive.google.com/file/d/{FILE_ID}/preview. I’ve used this method in several projects - works great. Just keep in mind that public files can be viewed by anyone with the link, so think about your security needs first.