Downloading Planet data with PHP cURL library

It is possible to access Planet's API using PHP library such as cURL library. Extra care must be taken, though, when dealing with binary data such as GeoTIFFs or thumbnails.

As an example, when requesting a scene using the Planet API, you would write a block of code like the following:

<?php
$url = "https://api.planet.com/v0/scenes/ortho/20150823_225309_0b09/full";
$api_key = "..."; // fill in real key here

$auth = "Basic " . base64_encode($api_key . ":");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $auth
)) ;
$a = curl_exec($ch);
?>

However, the response's header will be as follows:

HTTP/1.1 302 FOUND
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=utf-8
Date: Fri, 23 Oct 2015
19:58:58 GMT
Location: https://planet-imagery.s3.amazonaws.com/a3990573f23931deadb8f721ec98dc64?Signature=Sd9CVzRBc9BG839NDTXhwTdBvHI%3D&amp;Expires=1445630368&amp;AWSAccessKeyId=AKIAIXEW6OXYDUHRT3JQ&amp;response-content-disposition=attachment%3B%20filename%3D%2220150823_225309_0b09_visual.tif%22&amp;response-content-type=image/tiff

The Location line indicates that the Planet server redirects the call to a new URL address, from which the downloadable bundle is available.

When performing these operations using PHP, it is recommended to add an additional cURL line to ensure the automatic following of redirects.:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

However, this action action will result in Planet returning an error:

Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified

The issue arises because the redirect URL incorporates authentication, eliminating the need to provide the Authorization header, which cURL automatically reuses from the initial request.

Including both the Authorization header and authentication in the URL is problematic, leading to a server error.

To resolve this, configure cURL to not follow the redirect automatically. Instead, extract the redirect URL from the response and make a subsequent cURL request without using any authentication in the header:

<?php
$url = "https://api.planet.com/v0/scenes/ortho/20150823_225309_0b09/full";
$api_key = "..."; // fill in real key here

$auth = "Basic " . base64_encode($api_key . ":");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $auth
));
$a = curl_exec($ch);
$redirect_url = curl_getinfo($ch)["redirect_url"];
?>
Was this article helpful?
0 out of 1 found this helpful

Comments

0 comments

Article is closed for comments.