Search code examples
phpcurlmicrosoft-graph-apiimpresspages

How can i convert a https://graph.microsoft.com/v1.0/me/photo/$value response with php to an image


I'm trying to show a Microsoft Graph image on a php website. I receive the image from graph, but its not in the correct format.

The result is like ����JFIF``��C and so on

The problem is that I receive an image as result and not a json. But i'm not able to display the image with the code above.

> HTTP/1.1 200 OK
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: image/jpeg
ETag: "BB3972DD"
request-id: 1d3edddb-4278-43ac-be53-4a60861c7703
client-request-id: 1d3edddb-4278-43ac-be53-4a60861c7703
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Europe","Slice":"SliceA","Ring":"3","ScaleUnit":"002","Host":"AGSFE_IN_2","ADSiteName":"DUB"}}
Duration: 176.1934
Date: Wed, 28 Feb 2018 18:35:52 GMT
����JFIF``��C��C����"�� 
���}!1A

Thanks to the help of this community I was able to solve my problem. My working code is:

$ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => 'https://graph.microsoft.com/v1.0/me/photo/%24value',
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => null,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_HTTPHEADER => array(
            'authorization: Bearer '.ipDb()->selectValue('user','hash',array('id' => ipUser()->userId())),
            'content-type: image/jpeg; charset=utf-8'
        ) ,
    ));
    $response = curl_exec($ch);
    // Close the cURL resource, and free     system resources
    curl_close($ch);
    $returndata = 'photo <img src="data:image/jpeg;base64,' . base64_encode($response) . '"/>';
    return $returndata;

Solution

  • Since the $value URL returns the image binary, the line

        $returndata = 'photo <img src="data:image/jpeg;base64,' . base64_encode($res1['@odata.context']) . '"/>';
    

    should not use $res1['@odata.context'] but instead $response directly.

    So base64_encode($response) should be the last part of the img src tag.