Google Drive PHP API - Simple File Upload
Use this code to authenticate and upload a test file. You need to set <YOUR_REGISTERED_REDIRECT_URI>
(and also in console) to this document itself to authenticate.
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('<YOUR_CLIENT_ID>');
$client->setClientSecret('<YOUR_CLIENT_SECRET>');
$client->setRedirectUri('<YOUR_REGISTERED_REDIRECT_URI>');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
session_start();
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$data = file_get_contents('a.jpg');
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart'
));
print_r($createdFile);
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
How to use Google Drive API to upload files in my Drive (PHP)?
Upload to Google Drive with the Google Drive API - without composer
What you need for integrating the feature with a Website:
- Install the google-api-php-client
- Install the Google_DriveService client
- No matter how you upload files to Google Drive - you need some kind of credentials to show that you have access to the Drive in question (that is you need to authenticate as yourself).For this:
- If not already done - set up (for free) the Google Cloud console.
- Create a project.
- Enable the Drive API.
- Set up a consent screen.
- Go to
APIs & Services -> Credentials
and+Create Credentials
- There are several possibilities, in your case, it makes sense to create an
OAuth client ID
and choseApplication type: Web Application
- Specify the URL of your website with the form as
Authorized JavaScript origins
andAuthorized redirect URIs
- After creating the client - note down the
client ID
andclient secret
Now, you can put together Google's sample for authentication with the OAuth2 client with the creation of the Google Drive service object and Uploading to Google Drive, then incorporate it into a PHP File Upload.
Patching those code snippets together could look like following:
form.html
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
//create a Google OAuth client
$client = new Google_Client();
$client->setClientId('YOUR CLIENT ID');
$client->setClientSecret('YOUR CLIENT SECRET');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if(empty($_GET['code']))
{
$client->authenticate();
}
if(!empty($_FILES["fileToUpload"]["name"]))
{
$target_file=$_FILES["fileToUpload"]["name"];
// Create the Drive service object
$accessToken = $client->authenticate($_GET['code']);
$client->setAccessToken($accessToken);
$service = new Google_DriveService($client);
// Create the file on your Google Drive
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'My file'));
$content = file_get_contents($target_file);
$mimeType=mime_content_type($target_file);
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
}
?>
PHP file upload to Google Drive
You are missing an intermediary step in your code.
You need to save the uploaded file to disk locally first ( as a temporary file ) and then read that file back into either a variable or file handle which you would then pass in place of TESTFILE
in your $service->files->create()
call.
Something like this ...
$file_tmp = $_FILES["myFile"]["tmp_name"];
$file_type = $_FILES["myFile"]["type"];
$file_name = basename($_FILES["myFile"]["name"];
move_uploaded_file($file_tmp, "path/to/upload/".$file_name);
$file_data = file_get_contents("path/to/upload/".$file_name);
$file = new Google_Service_Drive_DriveFile();
$file->setName('HelloWorld');
$file->setDescription('A test document');
$result = $service->files->create(
$file,
array(
'data' => $file_data,
'mimeType' => $file_type,
'uploadType' => 'media'
)
);
But please remember to validate your file uploads for proper type, size, etc. as best practice.
PHP upload a file on google Drive
You forgot to read the quickstart first.
https://developers.google.com/drive/v3/web/quickstart/php
Full PHP Implement is in step 3 and the service is $service = new Google_Service_Drive($client);
How can I upload files to GoogleDrive in multipart type by using php-curl?
- You want to upload a file using
multipart/ralated
with Drive API v3. - You want to achieve this using PHP CURL.
- Your access token can be used for uploading the file to Google Drive.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
- In this case, I would like to propose to create the structure including the file and the metadata for
multipart/ralated
and request it.
Modified script:
When your script is modified, it becomes as follows.
public function uploadByCurl($uploadFilePath, $accessToken){
$handle = fopen($uploadFilePath, "rb");
$file = fread($handle, filesize($uploadFilePath));
fclose($handle);
$boundary = "xxxxxxxxxx";
$data = "--" . $boundary . "\r\n";
$data .= "Content-Type: application/json; charset=UTF-8\r\n\r\n";
$data .= "{\"name\": \"" . basename($uploadFilePath) . "\", \"mimeType\": \"" . mime_content_type($uploadFilePath) . "\"}\r\n";
$data .= "--" . $boundary . "\r\n";
$data .= "Content-Transfer-Encoding: base64\r\n\r\n";
$data .= base64_encode($file);
$data .= "\r\n--" . $boundary . "--";
$ch = curl_init();
$options = [
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => [
'Authorization:Bearer ' . $accessToken,
'Content-Type:multipart/related; boundary=' . $boundary,
],
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
];
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
}
- At this modified script, the filename and mimeType are retrieved from
$uploadFilePath
.
Note:
- Multipart upload can upload files less than 5 MB size. Please be careful this.
References:
Perform a multipart upload
Multipart upload: uploadType=multipart. For quick transfer of a small file (5 MB or less) and metadata that describes the file, all in a single request.
If I misunderstood your question and this was not the direction you want, I apologize.
Related Topics
Pkill -F Doesn't Work for Process Killing
Php: Multiple SQL Queries in One MySQL_Query Statement
Php, Display Image with Header()
More Concise Way to Check to See If an Array Contains Only Numbers (Integers)
How to Protect from Downloading a Video from a Site
Move_Uploaded_File() Function Is Not Working
Why Don't PHP Attributes Allow Functions
Generating Random Numbers Without Repeats
PHP Session Side-Effect Warning with Global Variables as a Source of Data
How to Get the Character from Unicode Code Point in PHP
Simple HTML Dom: How to Remove Elements
Reconstruct/Get Source Code of a PHP Function
How to Check If Time Is Between Two Times in PHP
Convert All Types of Smart Quotes with PHP
Single Quotes or Double Quotes for Variable Concatenation
PHP - Split String in Key/Value Pairs
Calculate Difference Between Two Dates Using Carbon and Blade