Getting duplicate files while trying to upload CSV files to google spreadsheet - php

I have applied file insertion code i.e to upload csv files to the google drive. All is working perfectly but I am getting duplicate files instead of getting one at a time. I have to upload two different files at a time but I am getting 4 files, need help in this case
This is google.php file where I have included "Google_Client.php","Google_DriveService.php" and file "insert.php" for the insertion in google drive which contain function insertFile($service, $title, $description, $parentId, $mimeType, $filename)
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'insert.php';
session_start();
$title = 'Total Likes/Reblogs';
$description = 'Total Likes/Reblogs';
$title1 = 'Total Likes/Reblogs per post';
$description1 = 'Total Likes/Reblogs per post';
$parentId = '';
$mimeType = 'text/csv';
$filename = 'total.csv';
$fileNamePerPost = 'totalPerPost.csv';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$service = new Google_DriveService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
insertFile($service, $title, $description, $parentId, $mimeType, $filename);
insertFile($service, $title1, $description1, $parentId, $mimeType, $fileNamePerPost);
} else {
$state = mt_rand();
$client->setState($state);
echo $_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>

Once OAuth 2.0 callback is handled, you need to stop executing. header(...) doesn't stop the script and inserts 2 files. Once the first execution is finished, redirection inserts the same files again.

Related

Google Drive API Code Authentication returns 500 error

Currently, I am working on We application in PHP, which will get Google Drive files and perform some operation on it.
I have created Google Project with name My Project, with credentials which allow me to download the credential json file. I have Used following two files as mentioned in the google documentation
https://developers.google.com/api-client-library/php/auth/web-app
index.php
<?php
require 'vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret_new.json');
//$client->setAccessType("online"); // offline access
//$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google-
drive/oauth2callback.php');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$drive = new Google_Service_Drive($client);
$optParams = array(
'fields' => 'nextPageToken, files(id, name)'
);
$files = $drive->files->listFiles($optParams);
if (count($files->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files->getFiles() as $file) {
echo $file->getName()." ".$file->getId()."<br/>";
}
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-
drive/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
oauth2callback.php
<?php
require_once 'vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret_new.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google-
drive/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE);
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google-drive/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
Once I run index.php file, it as me to login to google account and ask for required permission, once i access the permission it moves to redirect url which is oauth2callback.php file with code in url, but oauth2callback.php once it authenticate code it gives 500 error in line $client->authenticate($_GET['code']);
please give me solution for the same.

Exporting Large Google Files Via API

I'd like to know how to perform a large Google Slide export via API. I've followed the instructions here and it works fine with small files. If I try it with a large file, it just doesn't work. It is not returning errors or anything. The logic I'm using is the following:
<?php session_start();
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
//INCLUDE PHP CLIENT LIBRARY
require_once 'vendor/autoload.php';
// Create client object
$client = new Google_Client();
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/main.php');
$client->setAuthConfig("client_secret.json");
$client->addScope(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType('offline');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$pptFile = fopen("testPresentation.pptx", "w+");
$fileId = '1fx2uqe96NgsOabAv8S_mItlEbJ_NJSORqPitH55TMc';
try {
$file = $service->files->export($fileId,"application/vnd.openxmlformats-officedocument.presentationml.presentation", array("alt" => "media"));
$fileContent = $file->getBody()->getContents();
fwrite($outHandle, $fileContent);
} catch(Exception $e) {
print $e->getMessage();
}
//Close output file handle.
fclose($outHandle);
echo "Done.\n";
} else {
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/main.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
Like I said, it works with small files but not with large ones. One thing I've noticed is that when I do a var_dump($file); on the small file, the 'Content-Length' header has a size of "30083".
If I do the same on the large file, the 'Content-Length' header has a size of "0". I assume that exporting large files must be done different. I even run into this https://github.com/google/google-api-php-client/issues/1124 and tried the snippet there but had no success.

Transform PHP script into executable

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[]

Google Drive PHP API Download file

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.

Get post from Google+ without browser's authentication in google's account via PHP

I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");

Categories