Search code examples
phpcurlgoogle-apigoogle-contacts-api

How to update Google Contact's photo via PHP?


I am coding a site in PHP that will allow a user to view all his Google Contacts' names and profile photos in one long list. Then the user can drag-n-drop new photos to replace the existing profile photos.

However, I'm getting a 401 (unauthorized access) error when trying to update the photos.

I know the access_token is correct because it works in GET requests such as https://www.google.com/m8/feeds/photos/media/default/6f2?access_token=ya29.AHES6ZR_ZS7_u-8TbMOMaeaGW9q4F7tkuPxW6gFTulyBX

The docs have not helped much. See also these and these.

My code looks something like:

#the stuff that i echo out is just for debugging purposes
$apiVersion='3.0';
$access_token = $this->session->userdata('googleauth_access_token');

$url = 'https://www.google.com/m8/feeds/photos/media/default/' . $contactID;
$fp = fopen($image_location, "r");
$filesize = filesize($image_location);
echo '<img src="https://www.google.com/m8/feeds/photos/media/default/'. $contactID. '?access_token=' . $access_token.'"/><br/>';    
echo $image_location;
echo $filesize;
echo $url;
$requestHeaders=array('Content-type: image/*','If-Match: '.$eTag,'GData-Version: '.$apiVersion);
$requestHeaders[]='Authorization: Bearer '. $access_token;
print_r($requestHeaders);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_PUT, true);
curl_setopt($c, CURLOPT_INFILESIZE, $filesize);
curl_setopt($c, CURLOPT_INFILE, $fp);
curl_setopt($c, CURLOPT_VERBOSE, true);
curl_setopt($c, CURLOPT_HTTPHEADER, $requestHeaders);
$result = curl_exec($c);    
$curlGetInfo=curl_getinfo($c);
print_r($curlGetInfo);
curl_close($c);
fclose($fp);
echo $result;

I have also tried variations such as replacing the 'Authorization: Bearer' line with Authorization: GoogleLogin auth=ya29.AHES6ZR_ZS7_u-8TbMOMaeaGW9q4F7tkuPxW6gFTulyBX

Thanks for your help.


Solution

  • I can't believe it worked, but changing image/* to image/jpg fixed the 401 error problem.

    (This post tipped me off.)

    Also FYI, I'm still using $requestHeaders[]='Authorization: Bearer '. $access_token; rather than $requestHeaders[]='Authorization: GoogleLogin auth='. $access_token;