MS GRAPH PHP API Download .zip file

Miguel Grajeda 6 Reputation points
2023-03-29T19:49:19.38+00:00

Hi, 

I'm attempting to download a .zip file from an inbox via the MS GRAPH API using PHP. I got to the point where I could download the file but could only open it with WINZIP. If I try to unzip with Windows 11 I get an error: Windows cannot open the folder. The compressed (Zipped folder) 'file\path.zip" is invalid. 

I looked at the file properties and noticed that the Archive tab shows ZIP Archive for the file I downloaded from the inbox and ZIP Volume for the file downloaded via the API. 

I'll paste the two functions I'm using to accomplish this task. 

public function getAttachment($email, $messageId, $attachmentId, $attachmentName, $filepath, $accessToken)
	{
		$requestUrl = 'https://graph.microsoft.com/v1.0/users/'. $email .'/messages/'. $messageId .'';
		$requestUrl .= '/attachments/'. $attachmentId .'/$value';

		$requestHeaders = array("Authorization: Bearer $accessToken",
								"Content-Disposition: attachment; filename=$attachmentName",
								"Accept-Encoding: gzip, deflate",
								"User-Agent: MyApplication/1.0");
        // verifying my header
		var_dump($requestHeaders);
								
									
		$response = $this->graphDownloadGet($requestHeaders, $requestUrl, $filepath);
		return $response;
		
	}



	private function graphDownloadGet($requestHeaders, $requestUrl, $filepath)
	{
		$curl = curl_init();
		
		curl_setopt($curl, CURLOPT_HEADER, TRUE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_BINARYTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, FALSE);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeaders);
		curl_setopt($curl, CURLOPT_URL, $requestUrl);

		$response = curl_exec($curl);

		if(curl_errno($curl)){
        echo 'error:' . curl_error($curl);
		}
		
		// Get the HTTP status code
		$http_status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

		curl_close($curl);

		file_put_contents($filepath, $response);
		return (filesize($filepath) > 0)? true : false;
		
	}

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
13,329 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.