Search code examples
phpchartscomposer-php

Upload files to onedrive with php


I've been trying to load data onto my OneDrive using PHP for a long time. I've already read a lot about this and also found a project on github.

Now I tried this tutorial, but I can't get any further. https://www.webshark.ee/how-to-upload-files-from-server-to-microsoft-onedrive-using-rest-api-and-php/

I create a app in microsoft azure, to get the client id and more.. I downloaded the package with composer.

composer requires microsoft/microsoft-graph

I then created my script based on the first example in the tutorial. What I don't know is how to integrate the vendor from composer

my script looks like:

$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' => '[email protected]',
        'password' => 'your-password'
    ],
])->getBody()->getContents());
$user_accessToken = $user_token->access_token;

$graph = new Graph();
$graph->setAccessToken($user_accessToken);
?>

Currently I only get an error message when running the first script Warning: Undefined variable $guzzle in C:\xampp_neu\htdocs\test1\src\test.php on line 6


Solution

  • Guzzle is a HTTP client for PHP, and this warning is telling you that the Guzzle client is not defined. There are several steps to remedy this.

    First, install it via Composer by running the following:

    composer require guzzlehttp/guzzle
    

    Second, in order to use Composer packages in your PHP script, you'll need to include the Composer autoloader at the top of the file. This will load all of the packages you're using in the current script while skipping any installed packages that won't be used:

    <?php
    require_once 'vendor/autoload.php';
    

    And last, you'll need to instantiate the Guzzle client before its first usage:

    $guzzle = new GuzzleHttp\Client();
    

    Unrelated to your question, but you'll notice a further error unless you use the fully qualified namespace for the Graph() class:

    $graph = new Microsoft\Graph\Graph();