Triggering Browser Downloads in PHP via Amazon S3
When you retrieve an object from Amazon S3 using the AWS SDK for PHP, the default behavior is often to stream the raw byte content directly to the output buffer. If your script ends with echo $obj->body;, the browser interprets this as text or HTML unless explicitly told otherwise. To force a file downloadâlike serving test.jpg instead of displaying itâyou must manipulate the HTTP response headers before any data is sent.
The specific header required for this behavior is Content-Disposition. When set to attachment, browsers are instructed to prompt the user with a "Save As" dialog rather than attempting to render the file inline. Without this header, or if it is omitted entirely, modern browsers will attempt to display images, PDFs, and other media types directly in the viewport.
In your current implementation, you are correctly fetching the object headers using get_object_headers. However, there is a subtle issue in how you are constructing the request for the actual download. You are attempting to pass the content type from the headers array via $objInfo->header['_info']['content_type']. While the intention is sound, relying on nested arrays like _info depends heavily on the specific version of the AWS SDK you are using and can lead to undefined index errors if the structure differs slightly.
A more robust approach involves explicitly setting the Content-Disposition, Content-Type, and Cache-Control headers within the $options array passed to get_object(). This ensures that regardless of the internal data structure of the previous call, your download logic remains consistent.
Here is a refined pattern for downloading a file:
require_once('vendor/autoload.php'); // Assuming composer installation for modern SDKs
use Aws\S3\S3Client;
$bucket = 'my_bucket';
$key = 'test.jpg';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1', // Update to your specific region
'credentials' => [
'key' => $key,
'secret' => $secret
]
]);
// Fetch the object with explicit headers for download behavior
$command = $s3->getCommand('GetObject', [
'Bucket' => $bucket,
'Key' => $key,
'AcceptRanges' => 'bytes', // Recommended for partial content support
]);
$result = $s3->execute($command);
// Construct the response headers manually to ensure compatibility
$headers = [
'Content-Type' => $result['ContentType'],
'Content-Disposition' => 'attachment; filename="' . basename($key) . '"',
'Cache-Control' => 'private, max-age=86400' // Optional: controls caching behavior
];
header('Content-Type: ' . $headers['Content-Type']);
header('Content-Disposition: ' . $headers['Content-Disposition']);
header('Cache-Control: ' . $headers['Cache-Control'], true);
header('Content-Length: ' . strlen($result['Body']->getContents()), true);
In this example, we separate the retrieval of metadata from the header manipulation. By reading $result['ContentType'] directly from the executed command result, we avoid parsing complex nested arrays. We then use PHP's native header() function to inject these values into the HTTP response stream. This is critical because the S3 client object itself does not automatically flush headers to the browser; it only provides access to the body stream.
One potential pitfall to consider is filename encoding. If your file contains special characters in its name, simply appending the basename might result in a corrupted filename when saved by the user. In production environments, you might want to URL-decode the key or sanitize the filename string before injecting it into the Content-Disposition header value.
Additionally, be aware of browser security policies regarding CORS if your application serves these files from a different domain than where the download is initiated. If you require users to click a link generated by your PHP script on a third-party site, ensure that the S3 bucket policy allows the necessary cross-origin requests, or configure your own web server to handle the redirection appropriately.
For developers working within the Laravel ecosystem, managing these low-level HTTP headers often feels disconnected from the framework's routing conventions. While you can certainly handle this via raw Response objects in a controller, using packages that abstract S3 interactions or leveraging existing services like LaravelCompany can streamline how you manage asset delivery and storage logic without writing verbose header manipulation code every time.
Ultimately, the responsibility lies with the PHP script to tell the browser exactly what is happening. By explicitly setting Content-Disposition: attachment, you bypass the default rendering behavior and ensure users can reliably save your S3 assets.