2014-02-12 55 views
1

我正在使用谷歌驅動器文件上傳代碼。以下代碼在瀏覽器中正確運行。但是,如果我嘗試這樣做,我們錯誤爲:fgets()期望參數1是資源,字符串給出 我已經嘗試了很多解決方案,但它不工作。請指導我如何使用此代碼的Web服務上傳文件到谷歌驅動器。使用php web服務將文件上傳到谷歌驅動器

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); 

} 

感謝

回答

0

STDIN是一個命令行指令,它不是一個直接有效的PHP語句.. 我所做的就是:

$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)); 

多執行之後,您就在json文件token.json中獲取您的身份驗證信息...並且您可以使用以下內容來上傳...:

$service = new Google_DriveService($client); 

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

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

一旦你得到你的JSON不要再次運行頂級代碼...只需使用token.json每次上傳/下載....

相關問題