简体   繁体   English

如何使用php将文件上传到我的谷歌驱动器(即不是最终用户)

[英]How can I upload files into MY google drive (ie. not the end user's) using php

I want to use My Google drive for storing my files which users will upload on my website. 我想使用My Google驱动器存储用户将在我的网站上传的文件。 Here is the code what I am using so far. 这是我到目前为止使用的代码。

<!-- this is my index.php-->
<?php
ob_start();
error_reporting(E_ALL);
 ini_set('display_errors', '1');
require("functions.php");
session_start();
header('Content-Type: text/html; charset=utf-8');
$authUrl = getAuthorizationUrl("", "");
?>
<!DOCTYPE html>
<html lang="fi">
<head>
    <title>Google Drive Login and Upload</title>
    <meta charset="UTF-8">
</head>
<body>
<a href=<?php echo "'" . $authUrl . "'" ?>>Authorize</a>
</body>
</html>


<!--This is my fileUpload.php-->
<?php
ob_start();
require_once("functions.php");
session_start();

header('Content-Type: text/html; charset=utf-8');

global $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$client = new Google_Client();
$client->setClientId($CLIENT_ID);
$client->setClientSecret($CLIENT_SECRET);
$client->setRedirectUri($REDIRECT_URI);
$client->setScopes('email');

$authUrl = $client->createAuthUrl();    
getCredentials($_GET['code'], $authUrl);

$userName = $_SESSION["userInfo"]["name"];
$userEmail = $_SESSION["userInfo"]["email"];

?>
<!DOCTYPE html>
<html lang="fi">
<head>
    <title>Logged in</title>
    <meta charset="UTF-8">
</head>
<body>

    Hello <?php echo $userName; ?>!
    <br>
    <?php echo $userEmail; ?>

    <br><br><br>

    <form enctype="multipart/form-data" action="formAction.php" method="POST">
        <input type="file" name="file" required>
        <br><br>
        <label for="folderName">Folder name, this either uploads file to an existing folder or creates a new one based on the name</label>
        <br>
        <input type="text" name="folderName" placeholder="My cat Whiskers">

        <br><br>
        <input type="submit" name="submit" value="Upload to Drive">
    </form>

</body>
</html>

<!-- this is my formaction.php where the action goes after submitting the file upload form-->
<?php
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Oauth2.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';
session_start();

header('Content-Type: text/html; charset=utf-8');

// Init the variables
$driveInfo = "";
$folderName = "";
$folderDesc = "";

// Get the file path from the variable
$file_tmp_name = $_FILES["file"]["tmp_name"];

// Get the client Google credentials
$credentials = $_COOKIE["credentials"];

// Get your app info from JSON downloaded from google dev console
$json = json_decode(file_get_contents("composer.json"), true);
$CLIENT_ID = $json['web']['client_id'];
$CLIENT_SECRET = $json['web']['client_secret'];
$REDIRECT_URI = $json['web']['redirect_uris'][0];

// Create a new Client
$client = new Google_Client();
$client->setClientId($CLIENT_ID);
$client->setClientSecret($CLIENT_SECRET);
$client->setRedirectUri($REDIRECT_URI);
$client->addScope(
    "https://www.googleapis.com/auth/drive", 
    "https://www.googleapis.com/auth/drive.appfolder");

// Refresh the user token and grand the privileges
$client->setAccessToken($credentials);
$service = new Google_Service_Drive($client);

// Set the file metadata for drive
$mimeType = $_FILES["file"]["type"];
$title = $_FILES["file"]["name"];
$description = "Uploaded from your very first google drive application!";

// Get the folder metadata
if (!empty($_POST["folderName"]))
    $folderName = $_POST["folderName"];
if (!empty($_POST["folderDesc"]))
    $folderDesc = $_POST["folderDesc"];

// Call the insert function with parameters listed below
$driveInfo = insertFile($service, $title, $description, $mimeType, $file_tmp_name, $folderName, $folderDesc);

/**
* Get the folder ID if it exists, if it doesnt exist, create it and return the ID
*
* @param Google_DriveService $service Drive API service instance.
* @param String $folderName Name of the folder you want to search or create
* @param String $folderDesc Description metadata for Drive about the folder (optional)
* @return Google_Drivefile that was created or got. Returns NULL if an API error occured
*/
function getFolderExistsCreate($service, $folderName, $folderDesc) {
    // List all user files (and folders) at Drive root
    $files = $service->files->listFiles();
    $found = false;

    // Go through each one to see if there is already a folder with the specified name
    foreach ($files['items'] as $item) {
        if ($item['title'] == $folderName) {
            $found = true;
            return $item['id'];
            break;
        }
    }

    // If not, create one
    if ($found == false) {
        $folder = new Google_Service_Drive_DriveFile();

        //Setup the folder to create
        $folder->setTitle($folderName);

        if(!empty($folderDesc))
            $folder->setDescription($folderDesc);

        $folder->setMimeType('application/vnd.google-apps.folder');

        //Create the Folder
        try {
            $createdFile = $service->files->insert($folder, array(
                'mimeType' => 'application/vnd.google-apps.folder',
                ));

            // Return the created folder's id
            return $createdFile->id;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
}

/**
 * Insert new file in the Application Data folder.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param string $title Title of the file to insert, including the extension.
 * @param string $description Description of the file to insert.
 * @param string $mimeType MIME type of the file to insert.
 * @param string $filename Filename of the file to insert.
 * @return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
 */
function insertFile($service, $title, $description, $mimeType, $filename, $folderName, $folderDesc) {
    $file = new Google_Service_Drive_DriveFile();

    // Set the metadata
    $file->setTitle($title);
    $file->setDescription($description);
    $file->setMimeType($mimeType);

    // Setup the folder you want the file in, if it is wanted in a folder
    if(isset($folderName)) {
        if(!empty($folderName)) {
            $parent = new Google_Service_Drive_ParentReference();
            $parent->setId(getFolderExistsCreate($service, $folderName, $folderDesc));
            $file->setParents(array($parent));
        }
    }
    try {
        // Get the contents of the file uploaded
        $data = file_get_contents($filename);

        // Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true'
        $createdFile = $service->files->insert($file, array(
            'data' => $data,
            'mimeType' => $mimeType,
            'uploadType'=> 'multipart'
            ));

        // Return a bunch of data including the link to the file we just uploaded
        return $createdFile;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

echo "<br>Link to file: " . $driveInfo["alternateLink"];

?>

The Problem I getting is, When a user upload a file it doesn't come to my google drive But it goes to that user's Drive. 我遇到的问题是,当用户上传文件时,它不会来到我的谷歌驱动器但它会转到该用户的驱动器。 :( What I do not want. I want to store that file into my Google drive. :(我不想要的。我想将该文件存储到我的Google驱动器中。

Please help!! 请帮忙!! Thanks. 谢谢。

If you're successfully uploading files to the user's Google Drive, then congratulations. 如果您已成功将文件上传到用户的Google云端硬盘,那么恭喜您。 You're nearly there. 你快到了。 The only thing you need to change is how you get the access token. 您需要更改的唯一方法是获取访问令牌。 See How do I authorise an app (web or installed) without user intervention? 请参阅如何在没有用户干预的情况下授权应用程序(Web或已安装)? (canonical ?) (规范?)

Check this out 看一下这个

require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';

$client = new Google_Client();
// create an app in google and use credential form that app
$client->setClientId('<HERE_YOUR_CLIENT_ID>');
$client->setClientSecret('<HERE_YOUR_CLIENT_SECRET>');
$client->setRedirectUri('<HERE_YOUR_REGISTERED_REDIRECT_URI>');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));

session_start();

if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
    } else
        $client->setAccessToken($_SESSION['access_token']);

    $service = new Google_Service_Drive($client);

    //Insert a file
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents('a.jpg');

    $createdFile = $service->files->insert($file, array(
          'data' => $data,
          'mimeType' => 'image/jpeg',
          'uploadType' => 'multipart'
    ));

    print_r($createdFile);

} else {
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
    die();
}

Before use this you must have a google app, and the sdk. 在使用之前,您必须拥有Google应用和sdk。

Thanks 谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用PHP备份服务器文件将文件从服务器上传到Google云存储到Google服务器? - How can I upload files to google cloud storage from my server to google's server using PHP to backup my server files? 如何使用 Google Drive API 上传我的 Drive (PHP) 中的文件? - How to use Google Drive API to upload files in my Drive (PHP)? 如何使用带有访问令牌的php将文件上传到Google驱动器 - how to upload files to google drive using php with access token 使用php curl将文件上传到Google云端硬盘 - Upload files to Google Drive using php curl 我如何在 php 中使用 google api 访问特定用户的 google 驱动器并对其进行管理 - How can i use google api in php to access a specific user's google drive and manage it 如果用户在字段中输入格式错误的条目,如何防止发送表单? 即。 数字字段中的字母 - How can I prevent my form being sent if a user writes misformated entries in my fields? ie. Letters in number fields 我无法使用php在我的Google云端硬盘中看到通过api创建的文件和文件夹 - I can't see the files and folders created via api in my Google Drive using php 如何将文件上传到谷歌驱动器中的特定文件夹 - Google 驱动器 API (PHP) - How can i upload file to a specific folder in google drive -Google drive API (PHP) 如何获得超过20个结果即。 60使用google place API与PHP? - How to get more than 20 results ie. 60 using google place API with PHP? Google云端硬盘PHP API:如何将所有文件保存在由我的应用创建的文件夹中,由用户或其他应用放置在该文件夹中 - Google Drive PHP API: How do I get all files in a folder created by my app, placed there by the user or another app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM