jackhammer013
jackhammer013

Reputation: 2295

Microsoft OneDrive SDK run as cron

Hi am using this OneDrive SDK . https://github.com/krizalys/onedrive-php-sdk . I am using PHP. What I need is to create a cronjob that will fetch my files in OneDrive and save it to my local directory. It works fine following the tutorial in the SDK. However, the way that SDK works is it needs you to be redirected to Microsoft account login page to be authenticated.

This will require a browser. My question, is it possible to do this by just running it in the backend like a cron? I can't seem to find a way to do it using the SDK. In Google, they will provide you a key to access the services without logging in every time. I am not sure about OneDrive.

$localPath = __DIR__.'/uploads/';
$today = date('Y-m-d');

$folder = $client->getMyDrive()->getDriveItemByPath('/'.$today);

echo "<pre>";

try {

$files = $folder->getChildren();
$createdDirectory = $localPath.$today;

// Check if directory exist
if(is_dir($createdDirectory)){

    echo "\n"." Directory ".$createdDirectory." already exists, creating a new one..";

    // Create new directory
    $uuid1 = Uuid::uuid1();
    $createdDirectory = $createdDirectory.$uuid1->toString();
    echo "\n".$createdDirectory." created..";
}

// Create directory
mkdir($createdDirectory);

echo "\n".count($files)." found for ".$today;

// Loop thru files inside the folder
foreach ($files as $file){
    $save = $file->download();
    // Write file to directory
    $fp = fopen($createdDirectory.'/'.$file->name, 'w');
    fwrite($fp, $save);
    echo("\n File ".$file->name." saved!");
}

} catch (Exception $e){
    die("\n".$e->getMessage());
}


die("\n Process Complete!");

My code is something like that in the redirect.php

Upvotes: 1

Views: 670

Answers (1)

Marc LaFleur
Marc LaFleur

Reputation: 33124

It doesn't look like that SDK supports the Client Credentials OAuth Grant. Without that, the answer is no. You may want to look at the official Microsoft Graph SDK for PHP which supports this via the Guzzle HTTP client:

$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
    'form_params' => [
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'resource' => 'https://graph.microsoft.com/',
        'grant_type' => 'client_credentials',
    ],
])->getBody()->getContents());
$accessToken = $token->access_token;

Upvotes: 2

Related Questions