googleworkspace / php-samples

PHP samples for Google Workspace APIs
Apache License 2.0
288 stars 347 forks source link

Upload Image in Google Drive Using Google Drive API with PHP Code Run on Web Server #78

Open shuja007 opened 3 years ago

shuja007 commented 3 years ago

How are you? Hope you all fine. I'm going to try image upload to my google drive using google drive API every thing is going to good i install composer.json file successfully through composer require google/apiclient:^2.0 and i download the credentials.json successfully but the problem is that when i'm going to Generating Access Token through php google-drive.php then i got the verification code but when i put the code into verification place its give me the error like

Fatal error: Uncaught Error: Undefined constant "STDIN" in C:\xampp\htdocs\imagebob\google-drive.php:41 Stack trace: #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} thrown in C:\xampp\htdocs\imagebob\google-drive.php on line 41

so the above error I resolved when someone told me to define the STDIN in top of the code in google-drive.php class but after when i define the STDIN in my code then I face new issue and I don't know about this error meaning can some one help me in this error the error is

Fatal error: Uncaught InvalidArgumentException: Invalid code in C:\xampp\htdocs\imagebob\vendor\google\apiclient\src\Google\Client.php:176 Stack trace: #0 C:\xampp\htdocs\imagebob\google-drive.php(44): Google_Client->fetchAccessTokenWithAuthCode('') shuja007/Shujaat#1 C:\xampp\htdocs\imagebob\google-drive.php(62): getClient() #2 C:\xampp\htdocs\imagebob\form.php(1): include('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\imagebob\vendor\google\apiclient\src\Google\Client.php on line 176

in below i'm going to explain my all code with separate classes please check and give me the right solution i'm new in this field so please explain me in briefly I don't know does i define "STDIN" in right place or not and told me please where is my error occur. Thanks to you all in advance.

form.php "This is my first class"

<?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 "This is my second class which I include the form.php class"

<?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 "the third class is there"

<?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, $file_name, $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;
}
?>