Search code examples
phpazureblobstorage

Download large file in PHP from Azure Blob Storage


I'm in the process of migrating a website offering large downloadable files (4GB and up) into Azure. I have successfully created the connection to the Azure storage account so I can retrieve the files. However the download a) takes ages to start and b) consumes loads of memory since I read the entire file into memory before actually sending the downloadable data to the client. Is there a way to read the file in chunks from the Storage account to avoid the delay and memory consumption? The current code looks like this:

$getBlobResult = $blobClient->getBlob($containerName,$FileName);
$blobProperties=($getBlobResult->getProperties());
$FileSize=$blobProperties->getContentLength();
// Send headers 
header ("Content-type: application/octet-stream");
header ("Content-Length: $FileSize");
header ("Content-Disposition: attachment; filename=\"$FileName\"");
// Send content of file
echo stream_get_contents($getBlobResult->getContentStream());

Solution

  • Serving the file to the user via a signed URL as @CodeBrauer suggests would be the most preferable solution since you don't have to pipe the data through your code/infrastructure at all.

    Though if that is at odds with your requirements, then you can try replacing:

    echo stream_get_contents($getBlobResult->getContentStream());
    

    With:

    fpassthru($getBlobResult->getContentStream());
    

    Which should just dump the stream straight out without needing virtually any buffer.

    https://www.php.net/manual/en/function.fpassthru