I have created a simple PHP script to play around with Google's Drive SDK. The plan is that eventually we will use Google Drive as a form of CDN for some of our web content (our company already has already upgraded to 1TB).
The code works to a degree, in that it successfully authenticates and uploads a file. The problem is, the file is always broken and cannot be viewed either with Drive itself, or by downloading.
The code is relatively simple, and just fetches an image from Wikipedia and attempts an upload:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
require_once 'Google/Service/Oauth2.php';
$client = new Google_Client();
//$client->setUseObjects(true);
//$client->setAuthClass('apiOAuth2');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setClientId('***');
$client->setClientSecret('***');
$client->setRedirectUri('***');
$client->setAccessToken(authenticate($client));
// initialise the Google Drive service
$service = new Google_Service_Drive($client);
$data = file_get_contents('http://upload.wikimedia.org/wikipedia/commons/3/38/JPEG_example_JPG_RIP_010.jpg');
// create and upload a new Google Drive file, including the data
try
{
//Insert a file
$file = new Google_Service_Drive_DriveFile($client);
$file->setTitle(uniqid().'.jpg');
$file->setMimeType('image/jpeg');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
));
}
catch (Exception $e)
{
print $e->getMessage();
}
print_r($createdFile);
?>
The print_r statement executes and we get information about the file. However, as I mentioned, the file is not viewable, and appears to be corrupt. Can anyone shed any light on what the issue may be?
After doing some more digging around in the docs (the current public docs are seriously out of date), I found that it's necessary to send another parameter as part of the insert() function's body parameter (the second argument in the function call).
Using the following:
$createdFile = $service->files->insert($doc, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'media', // this is the new info
));
I was able to get everything working. I'll leave the question here, as I think it will be very useful until such a time that Google actually updates the documentation for the PHP API.
Source info here
Your code seems to be ok.
Have You tried to download this file from Google Drive afterwards and look at it?
Also I know its abit stupid but have You tried to write file on disk right after using file_get_contents(). You know just to establish point where it goes bad for 100%.
Related
I am trying to convert a local Excel.xlsx file with all existent design, format and formulas existent in my local Excel file. How can I do that using Google API with PHP?
What I was doing but not working was :
$client = new \Google_Client();
$client->setApplicationName('Name');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig($_SERVER['DOCUMENT_ROOT'] . '/credentials.json');
$service = new Google_Service_Drive($client);
$fileID = '';
$path = $_SERVER['DOCUMENT_ROOT'] . '/includes/files/';
$fileName = 'MAIN.xlsx';//this is the file I want to convert to Google sheet
$filePathName = $path.$fileName;
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$file->setMimeType($mimeType);
$createdFile = $service->files->copy($file, array(
'data' => $filePathName,
'mimeType' => $mimeType,
'convert' => true,
));
But that is not working. How should I correct?
I believe your goal as follows.
You want to upload a XLSX file from the local PC to Google Document.
When the XLSX file is uploaded, you want to convert it to Google Spreadsheet.
You want to achieve this using googleapis for PHP.
Modification points:
In your script, the method of "Files: copy" is used. This method copies the file on Google Drive. So I think that this cannot be used for achieving your goal. I think that this is the reason of your issue.
From your error message, I thought that you might be using Drive API v3. I guess that this might be also the reason of your issue.
From above points, when your script is modified, it becomes as follows.
Modified script:
$service = new Google_Service_Drive($client); // Please use your $client here.
$path = $_SERVER['DOCUMENT_ROOT'] . '/includes/files/';
$fileName = 'MAIN.xlsx';//this is the file I want to convert to Google sheet
$filePathName = $path.$fileName;
$file = new Google_Service_Drive_DriveFile();
$file->setName('MAIN.xlsx');
$file->setMimeType('application/vnd.google-apps.spreadsheet');
$data = file_get_contents($filePathName);
$createdFile = $service->files->create($file, array(
'data' => $data,
'uploadType' => 'multipart'
));
printf("%s\n", $createdFile->getId());
Note:
In this modified script, it supposes that you have already been able to get and out values for Google Drive using Drive API. Please be careful this.
In this method, the maximum file size is 5 MB. Please be careful this. When you want to upload the large file, please use the resumable upload. Ref
References:
Upload file data
Create files
I'm fairly new to writing in PHP and I've hit a snag while developing a Google Drive connection. I'm trying to create a small widget for a WordPress site wherein users on the site can upload and download files from their Google Drives.
These users are from a closed GSuite Domain and I use a Domain-Wide Service account in order to authenticate and connect to the user's drives.
I am able to connect, retrieve a list of files, and successfully "download" a files contents, though, this download does not actually download a file to the computer, simply returns the contents.
References:
-Uploading: https://developers.google.com/drive/api/v3/manage-uploads
-Downloading: https://developers.google.com/drive/api/v3/manage-downloads
-- I need to place a download button on my page which will allow a user to select a file and download it to their computer without saving it on the server. Currently it just returns the content of the file which I can store in a variable, but I do not know how to have a client request it and download it.
I need an upload button as well but I am working on a solution that I believe will work. I've read many different articles suggesting Ajax, Node, etc...
Ajax:
Calling a PHP function from an HTML form in the same file?
Upload UI:
https://www.htmlgoodies.com/beyond/cms/create-a-file-uploader-in-wordpress.html
In my client initialization file:
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Drive::DRIVE);
$client->setSubject($user_to_impersonate);
$driveService = new Google_Service_Drive($client);
return $driveService;
In the php script that loads the widget on the page:
$drive_connection = getUserGoogleDriveService();
$retrieved_files = array();
$filesList = $drive_connection->files->listFiles();
foreach($filesList->files as $file)
{
array_push($retrieved_files, array(
'filename' => $file->name,
'fileid' => $file->id,
'file' => $file
));
}
$get_specific_file = array_search('example_file_name',
array_column($retrieved_files, 'filename'));
Edit: I added my code thus far. This code successfully lets me store and retrieve files from my array for further use. How would I tie this into a client side UI to upload files to the google "create" function.
I'm working on a project where I would like to use WebRTC to record a video from my PHP website and upload it to my YouTube channel. For the code below I am just trying to get an upload to work, as the video is saved on my server. I'm not clear on what kind of key or authorization I need to use. After reading and studying the documentation, I think I need to use a service account (key) to accomplish this?
https://developers.google.com/api-client-library/php/auth/service-accounts
I do not want users to log in/authenticate a google account. I would like the upload to happen from my website to my YouTube channel.
I don't have access to install with composer, so I have uploaded the google-api-php-client (v2.2.2) folder on my server.
I haven't been able to find any current examples that are closer to what I need, so I'm trying to mashup these pieces:
Uploads to Drive: https://developers.google.com/api-client-library/php/guide/media_upload
Uses the Service Account key(?): https://developers.google.com/api-client-library/php/auth/service-accounts
Upload Video: https://developers.google.com/youtube/v3/code_samples/php#upload_a_video
I'm getting Any guidance is appreciated. I am receiving a "This page isn't working" HTTP ERROR 500
Here is what my code currently looks like:
<?php
if (!file_exists('google-api-php-client/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
putenv('GOOGLE_APPLICATION_CREDENTIALS=I-Video/i-video-recording-0e9cbc2cad7a.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$file = new Google_Service_YouTube($client);
$result = $service->files->insert($file, array(
'data' => file_get_contents("data/1530103005236.webm"),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'
));
?>
I am using Google Drive SDK to upload files by PHP. now I want to get the Link as string so that I can store it in my Database. But I don't have any idea on how to get it.. this is the code in creating the file in google drive using PHP.
$file = new Google_DriveFile();
$file->setTitle( 'new_pdf' );
$file->setMimeType( 'application/pdf' );
$createdFile = $service->files->insert( $file, array(
'data' => $stringContent,
));
You want one of the properties of $createdFile.
The list of properties is at https://developers.google.com/drive/v2/reference/files
You probably want webContentLink, but it depends on how it is you intend to use the URL.
Here is my code to upload a file:
private function addFile(File $file, $folderProject, User $user) {
$fileToUpload = new Google_DriveFile();
$fileToUpload->setTitle($file->getName());
//set mime type
$fileToUpload->setMimeType($file->getMimeType());
//build parent and set id
$parent = new Google_ParentReference();
$parent->setId($folderProject->getId());
//set parent to file
$fileToUpload->setParents(array($parent));
$data = file_get_contents($file->getPath());
$createdFile = $this->service->files->insert($fileToUpload, array(
'data' => $data,
'mimeType' => $file->getMimeType(),
));
}
When I upload for example a docx using this PHP code the file append to be unreadable on the Google Drive website (it shows up the XML structure of the docx) and it is showing up like this in my Google Drive folder:
And when i try to upload a docx directly through Google Drive UI it showing up like this (what i want):
I'm pretty sure that the problem is coming from the fact the Google
Drive UI tries to open the file in a different way because i uploaded
it through my app, but i don't want that :)
(i have the same problem with other kind of files)
I tried to set the parameter 'convert' = true in the array but then i got this error during the upload:
..convert=true&uploadType=multipart&key=AI39si49a86oqv9fhb9yzXp7FCWL-cSqwFiClHZqS3Y3r9Hw8ujtSNlZEWZyFKBp_id7LUyFaZTJ97pMeb0XqHznycK7JJ9o_Q:
(500) Internal Error
Documentation: https://developers.google.com/drive/v2/reference/files/insert
=> But anyway i don't think to convert is the right solution, i just want to be able to see the content as if i uploaded the file through the Google Drive UI
If i open the docx from my Google Drive Sync folders and I edit and save it, I will be able to see it through the Google Drive UI (showing with the W logo)
I also getting the same problem.
But the difference is that , I am uploading pdf and able to view pdf in google drive UI.
I need to automatically convert it to google doc format by api code after adding new pdf.
If I change $mimeType = 'application/vnd.google-apps.document'; then got below error
https://www.googleapis.com/upload/drive/v2/files?convert=true&uploadType=multipart: (400) Bad Request
if I add optional parameter
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => TRUE
));
Then no change , only pdf upload no conversion takes place.
do u have any suggestion , where I need to exactly add for convert parameter ?