I am trying to upload files to google drive using below code
require_once 'google-api-php-client-master/src/google/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/drive');
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
/*$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getItems();
echo json_encode($files_list);*/
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("test");
$file->setMimeType('application/vnd.google-apps.folder');
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
'uploadType' => 'multipart'
));
echo "===".$fileId = $createdFile->id;
}
else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
and it is giving me insufficient permissions error.
Am i missing something?
I tried using Service account and it worked fine, Is Service account required to upload files using Google Drive API?
Related
Hi Im trying Google drive integration v3 in php to upload file from my web page i do not want to use picker. I have successfully done oauth and login. I can create a file in the drive but with empty data. the error i get is permission to write i have given public access to that folder. How can i solve this and write the content to that file.
My code after auth(successfull) redirect.
first.php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('conf/client_id.json');
//$scope='https://www.googleapis.com/auth/drive.file';
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Drive::DRIVE_FILE);
$client->addScope(Google_Service_Drive::DRIVE);
$client->addScope(Google_Service_Drive::DRIVE_APPDATA);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$data = file_get_contents("a.png");
// create and upload a new Google Drive file, including the data
$file = new Google_Service_Drive_DriveFile($client);
$file->setName('img_'.uniqid().'.png');
$file->setMimeType('image/png');
//$parent = new Google_ParentReference();
//$parent->setId("0B687nRLFFN08ZXg0WU9Zb3VQaEE");
//$file->setParents(array($parent));
//$file->setParents(array('setId'=>"0B687nRLFFN08ZXg0WU9Zb3VQaEE"));
$createdFile = $service->files->create($file, array(
'data' => file_get_contents("a.png"), //$data
'mimeType' => 'image/png',
'uploadType' => 'media'
));
}
else {
$redirect_uri='http://'.$_SERVER['HTTP_HOST'].'/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I am trying to create a script to upload my file to Google Drive. When I run it, it works perfectly. Here's the working code:
public function uploadToDrive()
{
$client = new Google_Client();
$client->setClientId(Mage::getStoreConfig('mtm_google/drive/client_id'));
$client->setClientSecret(Mage::getStoreConfig('mtm_google/drive/client_secret'));
$client->setRedirectUri(Mage::getStoreConfig('mtm_google/drive/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);
$file = new Google_Service_Drive_DriveFile();
$file->setName('analysis.csv');
$file->setDescription('A test document');
$data = file_get_contents('temp.csv');
$service->files->create($file, array(
'data' => $data,
'mimeType' => 'text/csv',
'uploadType' => 'multipart'
));
echo 'SUCCESS!';
unlink('temp.csv');
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
}
This script should be executable from console, and not executed from certain URL. When I try to execute this from console, nothing happens because session variables and redirects are something it can't handle. How can I modify this script in order to be executable from console?
Simply define/set variables : $_GET, $_SESSION, ....
Those variables can be passed like an arguments from console using $argv[]
I am trying to upload a tar.gz file (300MB) to Google drive but for some reason this is not working.
Have already tried to change the mime-type but with no success.
What I am doing wrong?
This is the code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.tar.gz');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
I had a problem on making the Google Drive API work. I want to allow public user to search on my file list and upload files to my Google Drive.
I created an API key on my developer console and added it to the following script and try to read a list of my files, but didn't work. It returned "500 Internal Server Error". Do I miss anything?
require_once 'google-api-php-client/src/Google/autoload.php';
$client = new Google_Client();
$client->setDeveloperKey("MY_API_KEY");
$client->addScope("https://www.googleapis.com/auth/drive");
$dr_service = new Google_Service_Drive($client);
$dr_results = $dr_service->files->listFiles(array('maxResults' => 10))
I tried to use ClientID (see the following code) and it works but I don't want to prompt the user to login to their google account and I want them to do everything on my account. Or how can I call the oauth with my account without prompting the user?
session_start();
require_once 'google-api-php-client/src/Google/autoload.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('MY_CLIENT_ID');
$client->setClientSecret('MY_CLIENT_SECRET');
$client->setRedirectUri('MY_URL');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$authUrl = $client->createAuthUrl();
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://MY_URL');
}
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Drive($client);
var_dump($service->files->ListFiles());
}
download the files from here google drive client in a folder google_drive.Then try this code
include the three files .
require 'google_drive/Google_Client.php';
require 'google_drive/contrib/Google_DriveService.php';
require 'google_drive/socialmedia_oauth_connect.php';
create new object of the classess.
$client_gd = new Google_Client();
$service = new Google_DriveService($client_gd);
$file=new Google_DriveFile();
set access token
if(isset($_GET['code']))
{
$authCode = $_REQUEST['code'];
$accessToken = $client_gd->authenticate($authCode);
$_SESSION['access_token_gd']=$accessToken;
$client_gd->setAccessToken($accessToken);
$about = $service->about->get();
$user=$about['permissionId'];
$_SESSION['gd_user']=$user;
$_SESSION['user_info_gd']=$about;
header('location:'.HOME.'?index_gd=1');
}
authenticate with google drive
$authUrl = $client_gd->createAuthUrl();
//$clientid = $gdsettings->gdclient_id;
// $clientsec = $gdsettings->gdclient_secret;
$redirecturi = HOME.'index.php';
$oauth = new socialmedia_oauth_connect();
$oauth->provider="Google";
global $apiConfig;
$oauth->client_id = $apiConfig['oauth2_client_id'];
$oauth->client_secret = $apiConfig['oauth2_client_secret'];
$oauth->scope="https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me https://docs.google.com/feeds/ https://docs.googleusercontent.com/ https://spreadsheets.google.com/feeds/";
$oauth->redirect_uri = $apiConfig['oauth2_redirect_uri'];
$oauth->approval_prompt = "force";
$oauth->Initialize();
$oauth->Authorize();
get the files
$accessToken=$_SESSION['access_token_gd'];
$client_gd->setAccessToken($accessToken);
//print_r($client_gd->getAccessToken());
//List of files
$arr = array();
$files = $service->files->listFiles();
$about = $service->about->get();
$user=$about['permissionId'];
//$_SESSION['gd_user']=$user;
//$_SESSION['user_info_gd']=$about;
$drivefiles = $files["items"];
foreach($drivefiles as $divefl )
{
echo $divefl['title'];
}
here is the full description you can read google drive client integration
I have problem with downloading file from google drive using php api. I managed to upload file to google drive in folder and $service->files->insert returns to me File Resource which has attribute downloadUrl but when I redirect to that url, it does not work. I get 401 error. Why is this happening? What do I need to do make this work?
Here's code:
<?php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrive/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();
header("Location: $authUrl");
and code.php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrivePayload/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setApprovalPrompt('force');
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['upload_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
}
if ($client->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("hello.exe");
$file->setDescription("LALALALALAL");
$file->setMimeType('application/x-msdos-program');
$parent = new Google_Service_Drive_ParentReference();
$parent->setId("zzz");
$file->setParents(array($parent));
$data = file_get_contents('hello.exe');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/x-msdos-program',
'uploadType' => 'multipart',
"visibility" => "DEFAULT"
));
header("Location: " . $createdFile->downloadUrl);
}
downloadUrl is exactly what it says, ie. the URL your PHP app can use to fetch the file. You would almost never redirect a browser to that URL, and if you did (you probably really don't want to), you'll need append a valid access token to the URL to fix the 401.