How to share file for anyone Google Drive API using PHP - php

I have been trying over and over, but could not reach any result.
the code is generating permission id and I don't know what that means.
Please do help if anyone succeeded in this before, I just want to share file publicly using the google drive api v2.0
$fileId = '18mWN0UWX_z-4A1gag85ou0Im-wvKfMZU-tibdVd8nxY';
$userPermission = new Google_Service_Drive_Permission(array(
'type' => 'anyone',
'role' => 'reader',
'emailAddress' => 'user#example.com'
));
$request = $service->permissions->create(
$fileId, $userPermission, array('fields' => 'id'));
$batch->add($request, 'user');
$domainPermission = new Google_Service_Drive_Permission(array(
'type' => 'domain',
'role' => 'reader',
'domain' => 'example.com'
));
$request = $service->permissions->create(
$fileId, $domainPermission, array('fields' => 'id'));
$batch->add($request, 'domain');
$results = $batch->execute();
foreach ($results as $result) {
if ($result instanceof Google_Service_Exception) {
// Handle error
printf($result);
} else {
printf("Permission ID: %s\n", $result->id);
}
}
} finally {
$service->getClient()->setUseBatch(false);
}

Here is my code snippet which was 2 years old.
$uplodedOriginalFile = new Google_Service_Drive_DriveFile();
$originallinkdata = file_get_contents($downloadlink['originallink']);
$uploadedfile = $service->files->insert($uplodedOriginalFile, array(
'data' => $originallinkdata,
'uploadType' => 'multipart',
));
$newPermission = new Google_Service_Drive_Permission();
//$newPermission->setValue($value);
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{
$service->permissions->insert($uploadedfile['id'], $newPermission);
}
catch (Exception $e)
{
print "An error occurred: " . $e->getMessage();
}
$publicOriginallink = "https://googledrive.com/host/".$uploadedfile['id'];
So you just need the inserted file Id and keep the permssion for anyone as reader and append the inserted file Id after "https://googledrive.com/host/ [newly inserted file id which is returned by google drive sdk]"

code snippet worked
$fileid =$createdFile['id'];
//--insert permission to file in public
$newPermission = new Google_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{$service->permissions->insert($fileid, $newPermission);}
catch (Exception $e){print "An error occurred: " . $e->getMessage();}
$publicOriginallink = "https://googledrive.com/host/".$fileid;
I just made few changes with Jai's code (Google_Permission) to match with my Google APIs Client Library version.

Related

Problem with upload image to google drive using php

On my site I use google api to upload images in folder. Actually, there is no official documentation from google how to use api using php, only python, js and etc. Current problem is that I get no errors, but file isn't uploading. I'm 100% sure that my service workers work (sorry for such bad english) properly. Below I put my php code for uploading images:
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('./credentials.json');
$client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
$client->setClientSecret('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');
$service = new Google_Service_Drive($client);
//counting amount of files in folder, there is no real reason in doing that
//it is just a test of connecting
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$options = [
'q' => "'" . $folder_id . "' in parents",
'fields' => 'files(id, name)'
];
//printing result
$results = $service->files->listFiles($options);
echo count($results->getFiles());
//trying to add file
$data = file_get_contents("../test.jpg");
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid(). '.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$new_file = $service->files->create($file, [
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
]);
print_r($new_file);
}
This is my standard upload code for uploading.
Try removing 'uploadType' => 'multipart', in your code.
I also cant see you setting the folder id when you upload your file which means its going to root directory.
// Upload a file to the users Google Drive account
try{
$filePath = "image.png";
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$fileMetadata = new Drive\DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Remember if you are using a service account, files are uploaded to the service accounts drive account unless you add the folder you want to upload the file to.
files list
// Print the next 10 events on the user's drive account.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Using the code which was suggested to me, this is full solution.
(Thanks everybody who helped me)
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setClientId('YOUR ID IN SECRET FILE');
$client->setClientSecret(YOUR SECRET IN JSON FILE);
$client->setRedirectUri(YOUR REDIRECT URI);
//you should register redirect uri
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAuthConfig('./credentials.json');
$service = new Google_Service_Drive($client);
try{
$filePath = "../test.jpg";
$folder_id = 'YOUR FOLDER ID';
$fileMetadata = new Google_Service_Drive_DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
}

Using the Google Drive API for PHP, What is the proper way to upload a file while setting the "keepRevisionForever" to true?

I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

How to create image ads using facebook ads api using

I am using Facebook ads api to manage Ads from my application and using fb PHP sdk 3.0 for this purpose.
I am trying to create image ads and using following code for the same.
$account_id = "<MY_ACOUNT_ID>";
$ad_account = new AdAccount($account_id);
$photo_data = new AdCreativePhotoData();
$photo_data->setData( array( AdCreativePhotoDataFields::URL => $data['url']) );
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => <MY_PAGE_ID>,
AdCreativeObjectStorySpecFields::PHOTO_DATA => $photo_data,
'link'=>$data['link']
));
$creative_params = array();
$creative = new AdCreative(null, $account_id);
$creative_params['name'] = 'MY TEST ADS FROM API';
$creative_params['link_url'] = '<LINK URL OF IMAGE/WEBSITE>';
$creative_params['object_story_spec'] = $object_story_spec;
$creative->setData( $creative_params );
try{
$creative->create();
$fields = array();
$params = array(
'name' => 'MY TEST IMAGE ADS : VISH',
'adset_id' => $data['adset_id'],
'creative' => array('creative_id' => $creative->id),
'status' => $data['status'],
);
try{
$ads = $ad_account->createAd($fields, $params);
return $ads->id;
} catch (Exception $e){
throw new Exception($e->getErrorUserTitle());
}
} catch (Exception $e){
throw new Exception($e->getErrorUserTitle());
}
This generate ads in Facebook but when i see its preview in ads manager panel , it show this error.
Can anybody tell me , how to fix this issue.

How to fix Fatal error: Class 'Google_Service_Drive_ParentReference' not found?

I get Fatal error: Class 'Google_Service_Drive_ParentReference' not found when I trying upload file to google drive. How can I fix it? I think the Api miss the class 'Google_Service_Drive_ParentReference' in Drive.php
insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
The api certainly simplified the entire process. Add field 'parents' during folder creation
$folder = new Google_Service_Drive_DriveFile(array(
'name' => 'sub-folder-name',
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => array('parent-id')
);
You don't need to call the class again just do it like this
$file = new Google_Service_Drive_DriveFile();
$file->setName($filename);
$file->setDescription($description);
$file->setParents(array($parentId));

Google Drive PHP API empty uploaded file

So I've been having weird issues with PHP upload with GAPI. The file actually gets created on the drive but for some reason the data doesn't make it to Google and it just creates a file with 0 bytes.
Here's my code:
function uploadFile($service, $title, $description, $parentId, $mimeType, $filepath) {
$mimeType = "image/png";
$title = "test.png";
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents();
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
//return $createdFile;
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
}
Everything is authenticated so I know that's not the problem. When I output $data, I get the mess of crap that you usually get when pulling a file so I know that's not the issue.. All of the scopes should be right but here they are anyways:
$client->addScope("https://www.googleapis.com/auth/drive");
$client->addScope("https://www.googleapis.com/auth/drive.file");
$client->addScope("https://www.googleapis.com/auth/drive.appdata");
$client->addScope("https://www.googleapis.com/auth/drive.scripts");
$client->addScope("https://www.googleapis.com/auth/drive.apps.readonly");
$client->addScope("https://www.googleapis.com/auth/drive.metadata.readonly");
$client->addScope("https://www.googleapis.com/auth/drive.readonly");
No documentation I can find on this problem so any help would be really appreciated!
I was able to figure this out and wanted to leave this for anyone else that might have this issue.
Ended up looking through the source code and noticed an If statement that was not getting fired.
Change
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
To
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'uploadType' => 'media' //add this for pdfs to work
));
It's just that easy! Hate it when it's that easy..

Categories