Answer the question
In order to leave comments, you need to log in
How to send form data from website to Google Drive?
Task: there is a site with a form. When the user fills out the form, the data should be written to a file and this file should be sent to me in Google Drive.
To solve this problem, I took a special client for google api: https://github.com/google/google-api-php-client
And documentation for it: https://developers.google.com/api-client-library/ p...
The documentation describes several methods of authorization. I chose "OAuth 2.0 for Server to Server Applications" because I need to send the file specifically to my drive, not to the user's.
Then I did everything according to the instructions , added the project to the Google Developers Console, generated a CLIENT ID and a P12 key.
Using the examples from the documentation, I wrote the following code:
<?php
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
$client_email = '***';
if (file_exists("key.p12")) {
$private_key = file_get_contents('key.p12');
}
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Drive($client);
DEFINE("TESTFILE", 'testfile-small.txt');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fwrite($fh, "TEST TEST TEST");
fclose($fh);
}
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("Hello World!.txt");
$result2 = $service->files->insert(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
Answer the question
In order to leave comments, you need to log in
Try to check for the existence of the key.p12 file and then load it. In general, show better the error that the Google API returns to you so it will be much clearer, so that you could be prompted.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question