微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Google Drive API 和在 Web 服务器上运行的 PHP 代码在 Google Drive 中上传图像

如何解决如何使用 Google Drive API 和在 Web 服务器上运行的 PHP 代码在 Google Drive 中上传图像

你好吗?希望你们一切都好。 我将尝试使用谷歌驱动器 API 将图像上传到我的谷歌驱动器,一切都会好起来我通过 composer require google/apiclient:^2.0 成功安装了 composer.json 文件strong> 并且我成功下载了 credentials.json 但问题是当我要通过 PHP google-drive.PHP 生成访问令牌时,我得到了验证代码,但是当我将代码放入验证位置时,它给了我这样的错误

致命错误:未捕获的错误:未定义的常量“STDIN”在 C:\xampp\htdocs\imagebob\google-drive.PHP:41 堆栈跟踪:#0 C:\xampp\htdocs\imagebob\google-drive.PHP(62): getClient() shuja007/Shujaat#1 C:\xampp\htdocs\imagebob\form.PHP(1): include('C:\xampp\htdocs...') #2 {main} 被抛出 C:\xampp\htdocs\imagebob\google-drive.PHP 第 41 行

因此,当有人告诉我在 google-drive.PHP 类中的代码顶部定义 STDIN 时,我解决了上述错误,但是在我定义了 STDIN 之后在我的代码中,然后我面临新问题,我不知道这个错误意味着有人可以帮助我解决这个错误错误

未捕获的 invalidargumentexception:C:\xampp\htdocs\imagebob\vendor\google\apiclient\src\Google\Client.PHP:176 中的代码无效:#0 C:\xampp\htdocs\imagebob\google-drive .PHP(52): Google_Client->fetchAccesstokenWithAuthCode('') #1 C:\xampp\htdocs\imagebob\google-drive.PHP(70): getClient() #2 C:\xampp\htdocs\imagebob\submit。 PHP(3): require('C:\xampp\htdocs...') #3 {main} 扔在 C:\xampp\htdocs\imagebob\vendor\google\apiclient\src\Google\Client.PHP 上线176

在下面我将用单独的类解释我的所有代码请检查并给我正确的解决方案我是这个领域的新手所以请简要解释我我不知道我是否定义了“STDIN”正确的地方与否并告诉我我的错误发生在哪里。提前谢谢大家。

form.PHP“这是我的第一堂课”

<?PHP include 'google-drive.PHP';?>
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h2>PHP Google Drive Api </h2>
<a href="submit.PHP?list_files_and_folders=1">Click here to list all files and folders</a>
<h2>File Upload</h2>
<form action="submit.PHP" method="post" enctype="multipart/form-data" name="image" >
<label for="">Choose File</label>
 <input type="file" name="file" >
 <input type="submit" name="submit" value="submit" >
 </form>
 </body>
 </html>

google-drive.PHP“这是我的第二个类,其中包含 form.PHP 类”

<?PHP
require __DIR__ . '/vendor/autoload.PHP';
define('STDIN',fopen("PHP://stdin","r"));
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setRedirectUri('http://localhost/imagebob/oauth2callback.PHP');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig('credentials.json');
$client->setAccesstype('offline');
$client->setPrompt('select_account consent');

$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accesstoken = json_decode(file_get_contents($tokenPath),true);
$client->setAccesstoken($accesstoken);
}

if ($client->isAccesstokenExpired()) {
// Refresh the token if possible,else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccesstokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n",$authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accesstoken = $client->fetchAccesstokenWithAuthCode($authCode);
$client->setAccesstoken($accesstoken);

if (array_key_exists('error',$accesstoken)) {
throw new Exception(join(',',$accesstoken));
}
}
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath),0700,true);
}
file_put_contents($tokenPath,json_encode($client->getAccesstoken()));
}
return $client;
}

$client = getClient();
$service = new Google_Service_Drive($client);
$optParams = array(
'pageSize' => 10,'fields' => 'nextPagetoken,files(id,name)'
 );
 $results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n",$file->getName(),$file->getId());
}
}?>

submit.PHP“第三节课到了”

<?PHP
error_reporting(E_ERROR | E_PARSE);
require __DIR__ . 'google-drive.PHP';
if( isset( $_POST['submit'] ) ){
if( empty( $_FILES["file"]['tmp_name'] ) ){
echo "Go back and Select file to upload.";
exit;
}
$file_tmp = $_FILES["file"]["tmp_name"];
$file_type = $_FILES["file"]["type"];
$file_name = basename($_FILES["file"]["name"]);
$path = "uploads/".$file_name;

move_uploaded_file($file_tmp,$path);

$folder_id = create_folder( "google-drive-test-folder" );

$success = insert_file_to_drive( $path,$file_name,$folder_id);

if( $success ){
echo "file uploaded successfully";
} else {
echo "Something went wrong.";
}
}
function create_folder( $folder_name,$parent_folder_id=null ){

$folder_list = check_folder_exists( $folder_name );

if( count( $folder_list ) == 0 ){
$service = new Google_Service_Drive( $GLOBALS['client'] );
$folder = new Google_Service_Drive_DriveFile();
$folder->setName( $folder_name );
$folder->setMimeType('application/vnd.google-apps.folder');
if( !empty( $parent_folder_id ) ){
$folder->setParents( [ $parent_folder_id ] );
}

$result = $service->files->create( $folder );
$folder_id = null;
if( isset( $result['id'] ) && !empty( $result['id'] ) ){
$folder_id = $result['id'];
}
return $folder_id;
}
return $folder_list[0]['id'];
}
function check_folder_exists( $folder_name ){
$service = new Google_Service_Drive($GLOBALS['client']);
$parameters['q'] = "mimeType='application/vnd.google-apps.folder' and name='$folder_name' and 
trashed=false";
$files = $service->files->listFiles($parameters);
$op = [];
foreach( $files as $k => $file ){
$op[] = $file;
}
return $op;
}
function get_files_and_folders(){
$service = new Google_Service_Drive($GLOBALS['client']);
$parameters['q'] = "mimeType='application/vnd.google-apps.folder' and 'root' in parents and 
trashed=false";
$files = $service->files->listFiles($parameters);
echo "<ul>";
foreach( $files as $k => $file ){
echo "<li>
{$file['name']} - {$file['id']} ---- ".$file['mimeType'];
try {
// subfiles
$sub_files = $service->files->listFiles(array('q' => "'{$file['id']}' in parents"));
echo "<ul>";
foreach( $sub_files as $kk => $sub_file ) {
echo "<li&gt {$sub_file['name']} - {$sub_file['id']} ---- ". $sub_file['mimeType'] ." </li>";
}
echo "</ul>";
} catch (\Throwable $th) {
// dd($th);
}
echo "</li>";
}
echo "</ul>";
}
function insert_file_to_drive( $file_path,$parent_file_id = null ){
$service = new Google_Service_Drive( $GLOBALS['client'] );
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $service->files->create(
$file,array(
'data' => file_get_contents($file_path),'mimeType' => 'application/octet-stream',)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
return $is_success;
}
if( isset( $_GET['list_files_and_folders'] ) ){
echo "<h1>Retriving List all files and folders from Google Drive</h1>";
get_files_and_folders();
}
function dd( ...$d ){
echo "<pre style='background-color:#000;color:#fff;' >";
print_r($d);
exit;
}
?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。