Загрузить файл в Google Drive с php/codeingiter

Я работаю в веб-приложении (php,codeigniter), где я хочу создать форму со многими другими полями, где пользователь может загружать файлы на мой диск Google без входа в свою учетную запись Google.

поэтому я сначала пробовал клиентскую библиотеку php из их примера в github. но это также не работает.

    //1. Follow the instructions to Create Web Application Credentials(https://developers.google.com/api-client-library/php/auth/web-app#creatingcred) 
    //2. Download the JSON credentials
    $this->load->library('google');
    //3. Set the path to these credentials using Google_Client::setAuthConfig:
    $client = new Google_Client();
    $client->setAuthConfig('./uploads/client_credentials.json');
    //4. Set the scopes required for the API you are going to call
    //$client->addScope(Google_Service_Drive::DRIVE);
    $client->addScope("https://www.googleapis.com/auth/drive");
    //. Set your application's redirect URI
    // Your redirect URI can be any registered URI, but in this example
    // we redirect back to this same page
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $client->setRedirectUri($redirect_uri);

    //6. In the script handling the redirect URI, exchange the authorization code for an access token:
    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    }

    $service = new Google_Service_Drive($client);

    if (isset($_REQUEST['logout'])) {
        unset($_SESSION['upload_token']);
    }

    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
        $client->setAccessToken($token);
        // store in the session also
        $_SESSION['upload_token'] = $token;
        // redirect back to the example
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

    // set the access token as part of the client
    if (!empty($_SESSION['upload_token'])) {
        $client->setAccessToken($_SESSION['upload_token']);
        if ($client->isAccessTokenExpired()) {
            unset($_SESSION['upload_token']);
        }
    } else {
        $authUrl = $client->createAuthUrl();
    }
    //$_SERVER['REQUEST_METHOD'] == 'POST' && $client->getAccessToken()
    if ($client->getAccessToken()) {
        // We'll setup an empty 1MB file to upload.
        DEFINE("TESTFILE", './uploads/my_file.txt');
        if (!file_exists(TESTFILE)) {
            $fh = fopen(TESTFILE, 'w');
            fseek($fh, 1024 * 1024);
            fwrite($fh, "!", 1);
            fclose($fh);
        }
        // This is uploading a file directly, with no metadata associated.
        $file = new Google_Service_Drive_DriveFile();
        $result = $service->files->create(
                $file, array(
            'data' => file_get_contents(TESTFILE),
            'mimeType' => 'application/octet-stream',
            'uploadType' => 'media'
                )
        );
        print_r($result);
        // Now lets try and send the metadata as well using multipart!
        $file = new Google_Service_Drive_DriveFile();
        $file->setName("Hello World!");
        $result2 = $service->files->create(
                $file, array(
            'data' => file_get_contents(TESTFILE),
            'mimeType' => 'application/octet-stream',
            'uploadType' => 'multipart'
                )
        );
        print_r($result2);
    }

autoload.php Файл загружается правильно внутри библиотеки с именем Google, я загрузил в моем коде. но я получаю пустую страницу, когда я запустил это. также я не понимаю этого $_GET['code'] переменная. что я должен на самом деле отправить запрос на получение как code

пожалуйста помоги.

0 ответов

Другие вопросы по тегам