0
votes

I'm using google drive api to upload a file to google drive using php, but it every time asking me for authentication code fof my application. I have followed the steps given in the URL below https://developers.google.com/drive/web/quickstart/quickstart-php

My Code:

require_once 'src/Google/autoload.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('url');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();

try{
    //Request authorization
    print "Please visit:<br/>$authUrl<br/>\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('document.txt');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'text/plain',
    ));
print_r($createdFile);
}catch(apiServiceException  $e){
    echo $e->getMessage();  
}

Response :

https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=REDIRECT_URL&client_id=CLIENT_ID&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&access_type=online&approval_prompt=auto
1
Where are the codes you're calling the API ? and please post the response as well - Raptor
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. - DaImTo
I have update my question - Ravi Gupta
what is fgets(STDIN)? - DaImTo
fgets(STDIN) is given into google api example insted of it i'm using authcode which is coming from above response url - Ravi Gupta

1 Answers

0
votes

I have did more debugging for this issue and last i can upload files to google drive using PHP. But for this we have to authorize the code using manually according to google api then we will get the refresh token and using that token we can upload file to google drive every time whout asking any key

I have added code here https://rgknowledgebase.wordpress.com/2015/06/05/php-upload-file-to-google-drive/