Search code examples
phpmicrosoft-graph-apimicrosoft-graph-sdks

How to upload a profile photo with MSGRAPH-SDK-PHP v2?


I've a young intern who need to implements msgraphv2 with PHP over a custom app we have.

Everything gone right with basics informations like services, phones, etc. We can read and write on our tenant, but the problem is with profile picture.

Is there anyone who know how to create a ProfilePhoto object, needed by the setPhoto method of user object?

$tokenRequestContext = new ClientCredentialContext(
    'MS_TENANT_ID',
    'MS_CLIENT_ID',
    'MS_CLIENT_SECRET',
);
$appClient = new GraphServiceClient($tokenRequestContext);
$appClient->users()->byUserId($userId)->setPhoto([myPic])->wait();

That's the [myPic] part we missed. We also tried to get the current profile pic (with success), and modify content, but it also failed.

$myPic = $appClient->users()->byUserId($userId)->photo()->content()->get()->wait();
if (null == $myPic) {
    return null;
}

$binary = $myPic->getContents(); // Success
$appClient->users()->byUserId($userId)->photo()->content()->put($binary)->wait(); // Failed with Argument #1 ($body) must be of type Psr\\Http\\Message\\StreamInterface, string given

Solution

  • Many thanks to @Ulrich Eckhardt, problem is solved.

    $tokenRequestContext = new ClientCredentialContext(
        'MS_TENANT_ID',
        'MS_CLIENT_ID',
        'MS_CLIENT_SECRET',
    );
    $appClient = new GraphServiceClient($tokenRequestContext);
    $streamInt = GuzzleHttp\Psr7\Utils::streamFor($binary);
    $appClient->users()->byUserId($userId)->photo()->content()->put($streamInt)->wait();
    

    With $binary the binary content of the photo, and $userId the MS Azure ID.