aaP_pcdrips
You're welcome. This is forum, I just try to guide people who don't know or stucked on something with my best.
I'm sorry, I'm not use Onedrive product, so I can't help you guide for this one since it will be include personal information like api key, etc. But I believe microsoft have their API documentation, Trust me, trying to learn will not hurt anybody
But I'll try to help you. Here's the steps how to Create your own backup using API in PHP. Remember, you can try it first using single txt file or single folder with some file in it and make sure that file / folder have been uploaded successfully to the Onedrive:
Prerequisites
- Microsoft Account: You need a Microsoft account with access to OneDrive.
- Register an Application with Azure AD: Go to Azure App Registrations and register an application to access Microsoft Graph API.
- Redirect URI: Use
http://localhost
for development.
- Permissions: In the API permissions, add
Files.ReadWrite
and Files.ReadWrite.All
for OneDrive access.
- Obtain Client ID and Client Secret: After registration, get the Client ID and Client Secret for OAuth.
Steps to Upload Files to OneDrive with PHP
1. Install Required PHP Libraries
You need the Microsoft Graph SDK for PHP and Guzzle HTTP client to handle API requests. Install them via Composer:
composer require microsoft/microsoft-graph guzzlehttp/guzzle
2. Authenticate with Microsoft Graph API
Using OAuth 2.0, you’ll get an access token to authenticate API requests. Here's a PHP script to get the token.
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
function getAccessToken($clientId, $clientSecret, $tenantId) {
$client = new Client();
$response = $client->post("https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token", [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'scope' => 'https://graph.microsoft.com/.default',
'grant_type' => 'client_credentials',
]
]);
$data = json_decode($response->getBody()->getContents(), true);
return $data['access_token'];
}
// Use your application's credentials
$clientId = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';
$tenantId = 'YOUR_TENANT_ID';
$accessToken = getAccessToken($clientId, $clientSecret, $tenantId);
3. Upload Files to OneDrive
With the access token, you can now upload files to OneDrive. This example uploads a single file. For folders, you’ll iterate over directory contents.
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
function uploadToOneDrive($accessToken, $filePath, $oneDriveFolder = 'backup-folder') {
$client = new Client();
// Set the file name and path
$fileName = basename($filePath);
$fileContent = file_get_contents($filePath);
// OneDrive upload URL
$url = "https://graph.microsoft.com/v1.0/me/drive/root:/$oneDriveFolder/$fileName:/content";
// Send the PUT request to upload the file
$response = $client->put($url, [
'headers' => [
'Authorization' => "Bearer $accessToken",
'Content-Type' => 'application/octet-stream',
],
'body' => $fileContent
]);
if ($response->getStatusCode() == 201) {
echo "File uploaded successfully!";
} else {
echo "Failed to upload file: " . $response->getBody();
}
}
// Path to the file you want to upload
$filePath = '/path/to/your/file.txt';
// Call the function to upload
uploadToOneDrive($accessToken, $filePath);
4. Uploading Multiple Files or an Entire Folder
To upload all files in a directory, you can loop through the folder’s contents and call uploadToOneDrive
for each file.
function uploadFolderToOneDrive($accessToken, $folderPath, $oneDriveFolder = 'backup-folder') {
$files = scandir($folderPath);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
$filePath = "$folderPath/$file";
if (is_file($filePath)) {
uploadToOneDrive($accessToken, $filePath, $oneDriveFolder);
}
}
}
}
// Path to the folder you want to upload
$folderPath = '/path/to/your/folder';
// Call the function to upload folder contents
uploadFolderToOneDrive($accessToken, $folderPath);
Explanation of Key Steps
- Get Access Token: We obtain an access token by authenticating with Microsoft’s OAuth 2.0 endpoint using the application’s credentials.
- Upload Files via PUT Request: We use Microsoft Graph API’s
PUT /me/drive/root:/path:/content
endpoint to upload file contents directly to OneDrive.
Important Notes
- Token Expiry: The token expires after an hour by default, so you may need to handle token refresh if using long-running scripts.
- Error Handling: For production use, add error handling to retry failed uploads and manage errors gracefully.
- Folder Creation on OneDrive: Ensure the OneDrive folder exists. To create folders, use the
POST /me/drive/root/children
endpoint to create a folder before uploading if necessary.
Additional Resources
Refer to the Microsoft Graph API documentation for more advanced usage, like managing large files and handling permissions.