Cara Mengunggah File ke Google Drive dengan API menggunakan PHP

0
(0)

oleh Vincy. Terakhir diubah pada 5 Agustus 2022.

Mengunggah file ke Google Drive secara terprogram dapat dilakukan oleh Google API. Ini menggunakan OAuth untuk mengautentikasi permintaan dan mengotorisasi akses.

Tutorial ini menjelaskan mengunggah file ke Google Drive menggunakan PHP. Ini memberikan skrip PHP sederhana untuk dengan mudah memahami Google API dan mengunggah file.

Itu juga menggunakan database untuk menyimpan detail file yang diunggah dengan referensi Google Drive.

Ini menangani kesalahan yang dapat terjadi karena alasan berikut selama proses pengunggahan.

  1. Ketika file biner kosong pada skrip PHP.
  2. Ketika pengguna gagal mengirimkan formulir dan melanjutkan untuk mengunggah tanpa data formulir.
  3. Saat permintaan OAuth Google gagal mendapatkan token akses.
  4. Ketika permintaan cURL ke Google API gagal mengembalikan kode status 200.

Pada unggahan yang berhasil tanpa ketidakpastian di atas, kode ini menunjukkan tautan Google Drive untuk melihat pratinjau file yang diunggah.

Gambar di bawah ini menunjukkan formulir unggah file dengan respons sukses dan gagal.

php google drive unggah

Cara membuat kredensial API untuk mengakses Google Drive

Masuk ke akun Google Anda dan buka konsol pengembang. Kemudian ikuti langkah-langkah di bawah ini untuk membuat kredensial API untuk mengakses Google Drive untuk mengunggah file.

  1. Buat proyek baru atau pilih proyek yang sudah ada dari header konsol Google.
  2. Klik Perpustakaan menu dan aktifkan API Google Drive. Gunakan filter untuk memilih API ini.
  3. Memilih Layar persetujuan OAuth menu untuk membuat aplikasi. Isi yang berikut ini untuk mendaftarkan aplikasi.
    • Nama aplikasi
    • email dukungan
    • domain resmi
    • detail kontak pengembang (email).
  4. Pilih Kredensial->Buat Kredensiallalu pilih ID klien OAuth. Kemudian, masukkan detail berikut.
    • Memilih Tipe aplikasi sebagai Aplikasi web.
    • Tambahkan asal JavaScript resmi.
    • Tambahkan URI pengalihan resmi.

Setelah menyelesaikan langkah-langkah ini, konsol akan menampilkan ID klien web Google dan kunci rahasia. Kredensial ini digunakan untuk proses otentikasi untuk mendapatkan akses ke Google Drive.

kredensial sumpah

Contoh struktur file aplikasi

Mari kita lihat kode contoh PHP yang dibuat untuk artikel ini untuk mengunggah file ke Google Drive. Gambar berikut menunjukkan struktur file dari contoh ini.

contoh unggah file google drive

File konfigurasi aplikasi

File PHP ini berisi konstanta yang digunakan dalam contoh ini. Kredensial API dan titik akhir disimpan sebagai konstanta PHP dengan file ini.

URI titik akhir yang dikonfigurasi dalam file ini adalah untuk menekan Google Drive API untuk tujuan berikut.

  • Untuk menyetel cakupan selama pengalihan OAuth.
  • Untuk mendapatkan token akses setelah otentikasi dengan kredensial API GOOGLE_WEB_CLIENT_ID dan GOOGLE_WEB_CLIENT_SECRET.
  • Untuk mengunggah file ke Drive
  • Untuk menambahkan metadata ke file yang diunggah

Itu AUTHORIZED_REDIRECT_URI adalah untuk mengatur panggilan balik. API akan memanggil URI ini dengan kode akses untuk melanjutkan unggahan file setelah otentikasi.

lib/Config.php

<?php

class Config
{

    const GOOGLE_WEB_CLIENT_ID = 'add client id';

    const GOOGLE_WEB_CLIENT_SECRET = 'add client secret';

    const GOOGLE_ACCESS_SCOPE = 'https://www.googleapis.com/auth/drive';

    const AUTHORIZED_REDIRECT_URI = 'https://domain-name/php-google-drive-upload/callback.php';

    const GOOGLE_OAUTH2_TOKEN_URI = 'https://oauth2.googleapis.com/token';

    const GOOGLE_DRIVE_FILE_UPLOAD_URI = 'https://www.googleapis.com/upload/drive/v3/files';

    const GOOGLE_DRIVE_FILE_META_URI = 'https://www.googleapis.com/drive/v3/files/';
}

?>

Formulir pendaratan dengan opsi unggah file

Ini adalah bentuk HTML sederhana yang memanggil titik akhir PHP upload.php pada mengirimkan. Data file diposting ke file PHP ini untuk diunggah ke direktori lokal dan ke Google Drive.

Saya baru saja mengelola validasi bidang dengan menggunakan HTML5 yg dibutuhkan atribut. Anda juga dapat menambahkan validasi JavaScript eksklusif untuk formulir unggah file ini.

Kami telah melihat kode untuk melakukan validasi file sisi server di PHP.

index.php

<?php
session_start();

?>
<html>
<head>
<title>How to upload file to Google drive</title>
<link rel="stylesheet" type="text/css" href="https://phppot.com/php/how-to-upload-files-to-google-drive-with-api-using-php/css/style.css" />
<link rel="stylesheet" type="text/css" href="css/form.css" />
<style>
input.btn-submit {
    background: #ffc72c url("google-drive-icon.png") no-repeat center left
        45px;
    text-align: right;
    padding-right: 45px;
}
</style>
</head>
<body>
    <div class="phppot-container tile-container">
        <form method="post" action="upload.php" class="form"
            enctype="multipart/form-data">
<?php if(!empty($_SESSION['responseMessage'])){ ?>
    <div id="phppot-message"
                class="<?php echo $_SESSION['responseMessage']['messageType']; ?>">
                <?php echo $_SESSION['responseMessage']['message']; ?>
    </div>
<?php
    $_SESSION['responseMessage'] = "";
}
?>
<h2 class="text-center">Upload file to drive</h2>
            <div>
                <div class="row">
                    <label class="inline-block">Select file to upload</label>
                    <input type="file" name="file" class="full-width"
                        required>

                </div>
                <div class="row">
                    <input type="submit" name="submit"
                        value="Upload to Drive"
                        class="btn-submit full-width">
                </div>
            </div>
        </form>

    </div>
</body>
</html>

File unggah kode PHP ke direktori, simpan ke database dan arahkan ke Google

Titik akhir tindakan bentuk HTML ini melakukan pengunggahan file ke direktori. Ini menyimpan jalur file ke database dan mengalihkan ke URI OAuth Google.

URI ini menetapkan cakupan, id klien aplikasi, dan jalur pengalihan (callback.php) untuk mendapatkan kode akses dari titik akhir API Google Drive.

Jika terjadi kesalahan, ia memanggil utilitas aplikasi untuk mengenali dan memandu pengguna dengan benar.

upload.php

<?php
session_start();
require_once __DIR__ . '/lib/Util.php';
$util = new Util();

if (! empty($_POST['submit'])) {
    require_once __DIR__ . '/lib/Config.php';

    require_once __DIR__ . '/lib/FileModel.php';
    $fileModel = new FileModel();

    if (! empty($_FILES["file"]["name"])) {
        $fileName = basename($_FILES["file"]["name"]);
        $targetFilePath = "data/" . $fileName;
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) {
            $fileInsertId = $fileModel->insertFile($fileName);
            if ($fileInsertId) {
                $_SESSION['fileInsertId'] = $fileInsertId;

                $googleOAuthURI = 'https://accounts.google.com/o/oauth2/auth?scope=" .
                urlencode(Config::GOOGLE_ACCESS_SCOPE) . "&redirect_uri=' .
                Config::AUTHORIZED_REDIRECT_URI . '&response_type=code&client_id=' .
                Config::GOOGLE_WEB_CLIENT_ID . '&access_type=online';

                header("Location: $googleOAuthURI");
                exit();
            } else {
                $util->redirect("error", 'Failed to insert into the database.');
            }
        } else {
            $util->redirect("error", 'Failed to upload file.');
        }
    } else {
        $util->redirect("error", 'Choose file to upload.');
    }
} else {
    $util->redirect("error", 'Failed to find the form data.');
}
?>

Tindakan panggilan balik untuk mendapatkan token akses dan melanjutkan pengunggahan file ke Google Drive

Halaman ini dipanggil oleh Google API setelah melakukan permintaan OAuth. API mengirimkan kode parameter saat memanggil URL pengalihan ini.

Ini memanggil getAccessToken() fungsi yang didefinisikan dalam kelas layanan. Ini melewati kredensial API untuk mendapatkan token akses.

Ketika token diterima, file ini membangun konten file dan meta file untuk diunggah ke Google Drive melalui permintaan cURL.

Itu uploadFileToGoogleDrive() menerima token akses dan informasi file untuk mengatur opsi cURL. Ini mengembalikan id file dari file yang diunggah ke Google Drive.

Kemudian, addFileMeta() Fungsi PHP menerima array metadata file. Ini mengembalikan data meta file Google Drive yang diterima sebagai respons cURL.

ID metadata ini digunakan dalam respons sukses untuk memungkinkan pengguna melihat file yang diunggah di Google Drive.

panggilan balik.php

<?php
session_start();
require_once __DIR__ . '/lib/Util.php';
$util = new Util();
if (isset($_GET['code'])) {

    require_once __DIR__ . '/lib/Config.php';

    require_once __DIR__ . '/lib/GoogleDriveUploadService.php';
    $googleDriveUploadService = new GoogleDriveUploadService();

    $googleResponse = $googleDriveUploadService->getAccessToken(Config::GOOGLE_WEB_CLIENT_ID, Config::AUTHORIZED_REDIRECT_URI, Config::GOOGLE_WEB_CLIENT_SECRET, $_GET['code']);
    $accessToken = $googleResponse['access_token'];

    if (! empty($accessToken)) {

        require_once __DIR__ . '/lib/FileModel.php';
        $fileModel = new FileModel();

        $fileId = $_SESSION['fileInsertId'];

        if (! empty($fileId)) {

            $fileResult = $fileModel->getFileRecordById($fileId);
            if (! empty($fileResult)) {
                $fileName = $fileResult[0]['file_base_name'];
                $filePath="data/" . $fileName;
                $fileContent = file_get_contents($filePath);
                $fileSize = filesize($filePath);
                $filetype = mime_content_type($filePath);

                try {
                    // Move file to Google Drive via cURL
                    $googleDriveFileId = $googleDriveUploadService->uploadFileToGoogleDrive($accessToken, $fileContent, $filetype, $fileSize);
                    if ($googleDriveFileId) {
                        $fileMeta = array(
                            'name' => basename($fileName)
                        );
                        // Add file metadata via Google Drive API
                        $googleDriveMeta = $googleDriveUploadService->addFileMeta($accessToken, $googleDriveFileId, $fileMeta);
                        if ($googleDriveMeta) {
                            $fileModel->updateFile($googleDriveFileId, $fileId);

                            $_SESSION['fileInsertId'] = '';
                            $driveLink = '<a href="https://drive.google.com/open?id=' . $googleDriveMeta['id'] . '" target="_blank"><b>Open in Google Drive</b></a>.';
                            $util->redirect("success", 'File uploaded. ' . $driveLink);
                        }
                    }
                } catch (Exception $e) {
                    $util->redirect("error", $e->getMessage());
                }
            } else {
                $util->redirect("error", 'Failed to get the file content.');
            }
        } else {
            $util->redirect("error", 'File id not found.');
        }
    } else {
        $util->redirect("error", 'Something went wrong. Access forbidden.');
    }
}
?>

Kelas layanan PHP untuk menyiapkan permintaan dan menekan Google Drive API melalui cURL

Kelas layanan berisi fungsi yang membangun permintaan PHP cURL untuk mencapai API Google Drive.

Semua permintaan cURL menggunakan metode POST untuk mengirimkan parameter ke titik akhir API.

Itu mendapat kode respons dan data dalam format yang ditentukan. Jika terjadi kesalahan cURL atau mendapatkan kode respons selain 200, ia akan mengeluarkan pengecualian.

Saat mendapatkan kode status 200, ia menerima referensi file Google Drive dan respons metadata JSON dengan tepat.

lib/GoogleDriveUploadService.php

<?php
require_once __DIR__ . '/Config.php';

class GoogleDriveUploadService
{

    public function getAccessToken($clientId, $authorizedRedirectURI, $clientSecret, $code)
    {
        $curlPost="client_id=" . $clientId . '&redirect_uri=' . $authorizedRedirectURI . '&client_secret=" . $clientSecret . "&code=" . $code . "&grant_type=authorization_code';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, Config::GOOGLE_OAUTH2_TOKEN_URI);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $curlResponse = json_decode(curl_exec($curl), true);
        $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($responseCode != 200) {
            $errorMessage="Problem in getting access token";
            if (curl_errno($curl)) {
                $errorMessage = curl_error($curl);
            }
            throw new Exception('Error: ' . $responseCode . ': ' . $errorMessage);
        }

        return $curlResponse;
    }

    public function uploadFileToGoogleDrive($accessToken, $fileContent, $filetype, $fileSize)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, Config::GOOGLE_DRIVE_FILE_UPLOAD_URI . '?uploadType=media');
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $fileContent);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: ' . $filetype,
            'Content-Length: ' . $fileSize,
            'Authorization: Bearer ' . $accessToken
        ));

        $curlResponse = json_decode(curl_exec($curl), true);
        $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($responseCode != 200) {
            $errorMessage="Failed to upload file to drive";
            if (curl_errno($curl)) {
                $errorMessage = curl_error($curl);
            }
            throw new Exception('Error ' . $responseCode . ': ' . $errorMessage);
        }
        curl_close($curl);
        return $curlResponse['id'];
    }

    public function addFileMeta($accessToken, $googleDriveFileId, $fileMeta)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, Config::GOOGLE_DRIVE_FILE_META_URI . $googleDriveFileId);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $accessToken
        ));
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fileMeta));
        $curlResponse = json_decode(curl_exec($curl), true);
        $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($responseCode != 200) {
            $errorMessage="Failed to add file metadata";
            if (curl_errno($curl)) {
                $errorMessage = curl_error($curl);
            }
            throw new Exception('Error ' . $responseCode . ': ' . $errorMessage);
        }
        curl_close($curl);

        return $curlResponse;
    }
}
?>

Kelas model PHP untuk membuat kueri dan parameter untuk menyisipkan, membaca, dan memperbarui log data file

Kelas model PHP ini mendefinisikan fungsi untuk melacak log database untuk file yang diunggah.

Dalam panggilan balik, ia menulis id file Google Drive dengan referensi id yang terakhir dimasukkan dalam sesi.

lib/FileModel.php

<?php
require_once __DIR__ . '/DataSource.php';

class FileModel extends DataSource
{

    function insertFile($fileBaseName)
    {
        $query = "INSERT INTO google_drive_upload_response_log (file_base_name, create_at) VALUES (?, NOW())";
        $paramType="s";
        $paramValue = array(
            $fileBaseName
        );
        $insertId = $this->insert($query, $paramType, $paramValue);
        return $insertId;
    }

    function getFileRecordById($fileId)
    {
        $query = "SELECT * FROM google_drive_upload_response_log WHERE id = ?";
        $paramType="i";
        $paramValue = array(
            $fileId
        );
        $result = $this->select($query, $paramType, $paramValue);
        return $result;
    }

    function updateFile($googleFileId, $fileId)
    {
        $query = "UPDATE google_drive_upload_response_log SET google_file_id=? WHERE id=?";
        $paramType="si";
        $paramValue = array(
            $googleFileId,
            $fileId
        );
        $this->update($query, $paramType, $paramValue);
    }
}
?>

File ini adalah kelas PHP Util sederhana yang hanya memiliki fungsi redirect seperti sekarang.

Kita dapat meningkatkan fungsi ini dengan menambahkan lebih banyak utilitas. Misalnya, ia dapat memiliki dekode enkode JSON untuk mengubah respons cURL menjadi array.

lib/Util.php

<?php

class Util
{
    function redirect($type, $message)
    {
        $_SESSION['responseMessage'] = array(
            'messageType' => $type,
            'message' => $message
        );
        header("Location: index.php");
        exit();
    }
}
?>

Langkah-langkah instalasi

Sebelum menjalankan contoh ini untuk mengunggah file ke Google Drive, lakukan langkah-langkah berikut. Ini akan membuat lingkungan pengembangan siap dengan konfigurasi dan sumber daya yang diperlukan.

  1. Konfigurasikan detail basis data dengan lib/DataSource.php. Kode sumber menyertakan file ini.
  2. Konfigurasikan kunci Google API dengan lib/Config.php. Juga, berikan domain dan subfolder untuk mengatur panggilan balik dengan AUTHORIZED_REDIRECT_URI.
  3. Impor skrip SQL di bawah ini ke database target Anda.

sql/struktur.sql

--
-- Table structure for table `google_drive_upload_response_log`
--

CREATE TABLE `google_drive_upload_response_log` (
  `id` int NOT NULL,
  `google_file_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `file_base_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `create_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `google_drive_upload_response_log`
--
ALTER TABLE `google_drive_upload_response_log`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `google_drive_upload_response_log`
--
ALTER TABLE `google_drive_upload_response_log`
  MODIFY `id` int NOT NULL AUTO_INCREMENT;

Unduh

Kembali ke Atas


Source link

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.


Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/widiyana/public_html/widiyanata.com/wp-includes/functions.php on line 5349

Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/widiyana/public_html/widiyanata.com/wp-includes/functions.php on line 5349