How to upload files from server to Microsoft OneDrive using REST API and PHP

How to upload files from server to Microsoft Sharepoint OneDrive using REST API and Microsoft own Graph SDK and PHP?

First install into your server using composer in command line Microsoft Graph SDK for PHP

composer require microsoft/microsoft-graphCode language: JavaScript (javascript)

Next you should fill in PHP credentials for authentication, you will get those (your-id-number, your-client-id-number, your-client-secret-number) from your Microsoft Azure portal (portal.azure.com). And your e-mail (your-email@email.com) and password (your-password) are same like e-mail and Sharepoint OneDrive login

<?php
$tenantId = 'your-id-number';
$clientId = 'your-client-id-number';
$clientSecret = 'your-client-secret-number';
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token';
$user_token = json_decode($guzzle->post($url, [
	'form_params' => [
		'client_id' => $clientId,
		'client_secret' => $clientSecret,
		'resource' => 'https://graph.microsoft.com/',
		'grant_type' => 'password',
		'username' => 'your-email@email.com',
		'password' => 'your-password'
	],
])->getBody()->getContents());
$user_accessToken = $user_token->access_token;

$graph = new Graph();
$graph->setAccessToken($user_accessToken);
?>
Code language: PHP (php)

And finally is upload part, there is upload for smaller files (less then 4MB) and bigger files, up-to 250MB

<?php
$file_name = 'name-to-file';
$filetype  = pathinfo( $_FILES['file-field']['name'], PATHINFO_EXTENSION );
$file = $file_name . $filetype;
$file_upload_path = 'folder-path-in-server';
$folder_in_onedrive = 'test/';
if (!file_exists($file_upload_path)) {
	mkdir($file_upload_path);
}
$uploadfile = $file_upload_path . basename( $file );

move_uploaded_file( $_FILES['file-field']['tmp_name'], $uploadfile );

$maxuploadsize = 1024 * 1024 * 4;
if (filesize($uploadfile) < $maxuploadsize) {
	$graph->createRequest("PUT", "/me/drive/root:/" . $folder_in_onedrive . $file . ":/content")->upload($uploadfile);
}
else {
	$uploadSession = $graph->createRequest("POST", "/me/drive/root:/" . $folder_in_onedrive . $file . ":/createUploadSession")
		->addHeaders(["Content-Type" => "application/json"])
		->attachBody([
			"item" => [
				"@microsoft.graph.conflictBehavior" => "replace"
			]
		])
		->setReturnType(Model\UploadSession::class)
		->execute();

	$file = $uploadfile;
	$handle = fopen($file, 'rb');
	$fileSize = fileSize($file);
	$chunkSize = 1024*1024*2;
	$prevBytesRead = 0;
	while (!feof($handle)) {
		$bytes = fread($handle, $chunkSize);
		$bytesRead = ftell($handle);

		$resp = $graph->createRequest("PUT", $uploadSession->getUploadUrl())
			->addHeaders([
				'Connection' => "keep-alive",
				'Content-Length' => ($bytesRead-$prevBytesRead),
				'Content-Range' => "bytes " . $prevBytesRead . "-" . ($bytesRead-1) . "/" . $fileSize,
			])
			->setReturnType(Model\UploadSession::class)
			->attachBody($bytes)
			->execute();

		$prevBytesRead = $bytesRead;
	}
}
?>
Code language: PHP (php)

Leave a comment

Your email address will not be published. Required fields are marked *