Reputation: 392
I want to make a webpage in which there will be an file input box, and the files which user uploads, should be saved into my Google Drive.
How do I achieve it using PHP?
I don't want to use composer
I need refreance to a good article with some indications
I checked on Google but I found articles to write on other's Drive, but not my own. Also, I checked the Drive API documentation, but I think its too professional for me! Please tell me how to make a simple uploading PHP page.
Upvotes: 5
Views: 15634
Reputation: 26836
What you need for integrating the feature with a Website:
APIs & Services -> Credentials
and +Create Credentials
OAuth client ID
and chose Application type: Web Application
Authorized JavaScript origins
and Authorized redirect URIs
client ID
and client 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);
}
?>
Upvotes: 17