Simple PHP cURL method for downloading file from Azure storage blob

2.7k Views Asked by At

I am uploading file from local server to Azure storage - blob container using Simple PHP cURL function. I taken code from below url .

https://stackoverflow.com/questions/41682393/simple-php-curl-file-upload-to-azure-storage-blob

Can someone tell me any link or code which I can download file from Azure storage - blob without any SDK and/or multiple files/libraries. It should be like a upload function.

Thanks in advance!

1

There are 1 best solutions below

2
On BEST ANSWER

This is the sample that I referred to. It's very detailed and may help you understand using cURL to request API, like Get Blob API.

Request:

GET https://myaccount.blob.core.windows.net/mycontainer/myblob
  x-ms-date: Mon, 24 Apr 2021 06:34:09 GMT
  x-ms-version: 2014-02-14
  Authorization: SharedKey myaccount:<signature_str>

You could refer to this.

<?php

$storageAccount = '';
$containerName = '';
$blobName = '';
$account_key = '';

$date = gmdate('D, d M Y H:i:s \G\M\T');
$version = "2019-12-12";

$stringtosign = "GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:". $date . "\nx-ms-version:".$version."\n/".$storageAccount."/".$containerName."/".$blobName;
$signature = 'SharedKey'.' '.$storageAccount.':'.base64_encode(hash_hmac('sha256', $stringtosign, base64_decode($account_key), true));
echo "\n\n" . $signature;

$header = array (
    "x-ms-date: " . $date,       
    "x-ms-version: " . $version,       
    "Authorization: " . $signature
);

$url="https://$storageAccount.blob.core.windows.net/$containerName/$blobName";
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
curl_exec ( $ch );
$result = curl_exec($ch);
echo "\n\n" . $result;

if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
}

file_put_contents('D://demo//downloaded.txt', $result); // save the string to a file

curl_close($ch);