1

i am using google drive file upload code. The following code runs correct in browser. But if i try to do it we error as : fgets() expects parameter 1 to be resource, string given I have tried many solution but its not working. Please guide me how to use this code for web service to upload file to google drive.

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';



function uploadFile()
{

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));


if(!defined("STDIN")) define("STDIN", "fopen('php://stdin','r')");

$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
//$authCode = trim(file_get_contents(STDIN));



// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('Test document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = file_get_contents('upload.txt');

$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'text/plain',
    ));

print_r($createdFile); 

}

Thanks

1 Answers1

0

STDIN is a command line instruction and it isn't a direct valid php statement .. What i did was :

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$authUrl = $client->createAuthUrl();
print $authurl

$authCode = ''; // insert the verification code that you get after going to url in $authurl
file_put_contents('token.json', $client->authenticate($authCode));

After executing this much you'll get your authentication info in the json file token.json ... And you can use the following to upload ... :

$service = new Google_DriveService($client);

$client->setAccessToken(file_get_contents('token.json'));

//Insert a file 
    ..... // rest the same

Once you get your json don't run the top codes again ... Just use the token.json everytime to upload/download ....