Follow

Downloading Planet data with PHP cURL

PHP can be used to access Planet's API, but if you are using PHP's cURL library, some care must be taken when requesting items such as GeoTIFFs or thumbnails.

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

$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, if we check the result of this short PHP script, we will see that the server has responded with the following:

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&Expires=1445630368&AWSAccessKeyId=AKIAIXEW6OXYDUHRT3JQ&response-content-disposition=attachment%3B%20filename%3D%2220150823_225309_0b09_visual.tif%22&response-content-type=image/tiff

The Location line indicates that the Planet server is redirecting you to a new URL, from which you can download the image in full.

Normally with PHP, we'd add an extra cURL option to automatically follow this redirect:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

However, if you try this, you will see that Planet returns 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 problem is that the redirect URL has authentication built into it so that we do not need to provide the Authorization header, which cURL is automatically reusing from the initial request.

In fact, providing both the Authorization header and authentication in the URL is problematic, which is why the server returns an error.

The solution in this situation is to not have cURL follow the redirect and extract the redirect URL from the response and make a second cURL request that does not use any authentication in the header:

$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 0 found this helpful
Have more questions? Submit a request

0 Comments

Article is closed for comments.