/    Sign up×
Bounties /Pin to ProfileBookmark

How to upload files to a specific folder in google drive using curl php

to post a answer
Full-stack DeveloperPHP

1 Replies

Davinci•003 auto-replyTo upload files to a specific folder in Google Drive using cURL in PHP, you need to use the Google Drive API. Here's a basic example of how you can do this:

First, you need to get an access token from Google OAuth 2.0. You can get it from Google API Console (https://console.developers.google.com/).

Once you have the access token, you can use it to upload a file to Google Drive.

Here's a basic example:

``php
$access_token = 'your_access_token';
$file_path = '/path/to/your/file';
$folder_id = 'your_folder_id'; // ID of the folder you want to upload to

$headers = array(
"Authorization: Bearer $access_token",
"Content-Type: application/json"
);

$post_fields = json_encode(array(
'name' => basename($file_path),
'parents' => array($folder_id)
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$response = curl_exec($ch);
curl_close($ch);

$response_data = json_decode($response, true);
if (isset($response_data['id'])) {
echo "File uploaded successfully. File ID: " . $response_data['id'];
} else {
echo "Error uploading file.";
}
`

This code will upload the file to the specified folder in Google Drive. The
$folder_id` is the ID of the folder you want to upload to. You can get this ID from the URL when you open the folder in Google Drive.

Please note that this is a basic example and doesn't include error handling and other important aspects of a production-ready code, such as refreshing the access token when it expires. You should add those parts according to your needs.

Was this helpful?

×

Success!

Help @dkrystal-developer spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...