Development
How to Serve Private Downloads With PHP

Serve private downloads with PHP by keeping the bytes outside the public document root, resolving an opaque document ID through a server-owned map, and authorizing the trusted actor before touching that document's file. After acceptance, open the mapped regular file, set fixed headers and copy only its bytes.
Hiding a page link is not that boundary. Another delivery path can serve a file without running the page's PHP permission check. Your actual web-server/storage configuration must keep private bytes behind the intended handler.
The complete original example below passed 83 checks on PHP 8.4.24, including 13 controlled GET/HEAD cases. It uses three tiny synthetic files and fixed synthetic principals. It does not implement or prove HTTP authentication, production entitlements, CDN protection or browser download behavior.
Serve private downloads with PHP after a server-owned decision
The handler receives an actor from an explicitly separate trusted identity boundary. A submitted user ID, query parameter or request header does not become an authenticated actor just because PHP can read it.
This example's product rule is exact document ownership. Two synthetic actors share the same role, but one cannot receive the other's document. The document ID selects a fixed map entry; it is never joined onto a directory as a user-supplied path or treated as a URL.
Unknown and denied requests use the same empty 404 response here. That is this example's deliberate policy, not a universal requirement for every product. It avoids returning private bytes, a filename or a length for a refused document.
Copy the complete delivery module
Save this exact module as private-download.php. Its syntax uses PHP 8 features; only PHP 8.4.24 was actually tested. The small 16KiB source ceiling and expected byte length are explicit policies for these stable demonstration files.
<?php
declare(strict_types=1);
/** Actor and document map are trusted server-owned inputs, not submitted user identities/paths. */
function privateDownloadResponse(?array $actor, string $method, string $documentId, array $documents): array
{
$refusal = ['status' => 404, 'length' => 0, 'stream' => null, 'send_body' => false];
if (!in_array($method, ['GET', 'HEAD'], true)) {
return array_replace($refusal, ['status' => 405]);
}
// Authorization precedes every filesystem lookup/open; a shared role alone is not enough.
if ($actor === null || !isset($actor['id']) || !is_string($actor['id'])
|| !isset($documents[$documentId]) || $actor['id'] !== $documents[$documentId]['owner']) {
return $refusal;
}
$entry = $documents[$documentId];
$failure = array_replace($refusal, ['status' => 500]);
if (is_link($entry['path']) || !is_file($entry['path'])) { return $failure; }
$stream = @fopen($entry['path'], 'rb');
if ($stream === false) { return $failure; }
$stat = fstat($stream);
if ($stat === false || ($stat['mode'] & 0170000) !== 0100000 || $stat['size'] < 0
|| $stat['size'] > 16384 || $stat['size'] !== $entry['bytes']) {
fclose($stream);
return $failure;
}
// Ownership of this one handle transfers to the emitter (or a caller that closes it).
return ['status' => 200, 'length' => $stat['size'], 'stream' => $stream, 'send_body' => $method === 'GET'];
}
/** Emits only fixed headers and file bytes. Never print diagnostics into this response. */
function emitPrivateDownload(array $response): array
{
$stream = $response['stream'];
try {
if (headers_sent()) { throw new RuntimeException('headers_already_sent'); }
http_response_code($response['status']);
header('Cache-Control: private, no-store');
if ($response['status'] !== 200) {
header('Content-Type: text/plain; charset=UTF-8');
header('Content-Length: 0');
if ($response['status'] === 405) { header('Allow: GET, HEAD'); }
return ['expected_copy_bytes' => 0, 'copied_bytes' => 0, 'complete' => true];
}
if (!is_resource($stream)) { throw new RuntimeException('stream_contract'); }
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="document.bin"');
header('Content-Length: ' . $response['length']);
$expected = $response['send_body'] ? $response['length'] : 0;
$copied = $response['send_body'] ? @fpassthru($stream) : 0;
// A partial copy cannot be withdrawn. Return a closed result, do not append an HTML error.
return ['expected_copy_bytes' => $expected, 'copied_bytes' => $copied === false ? null : $copied,
'complete' => is_int($copied) && $copied === $expected];
} finally {
if (is_resource($stream)) { fclose($stream); }
}
}
The early authorization checks precede every document filesystem lookup and open in source order. Only after acceptance do the regular-file checks and fopen() run. Length comes from fstat on the opened handle, then must match the map's expected immutable example length. A zero-byte file is valid; zero is not treated as “missing.”
The preparer transfers ownership of one handle to the emitter, or to a caller that explicitly closes it. The emitter closes it in finally for GET and HEAD. Its response array is trusted internal output, not request JSON or an object to accept from a client.
This does not establish safety against concurrent hostile filesystem changes or every symlink race. The fixture owns stable regular files; a production storage/versioning model needs its own review.
Keep response metadata fixed and byte-specific
For an accepted response, the emitter sets application/octet-stream, a fixed ASCII attachment filename, private, no-store and the opened file's observed length. PHP headers must be chosen before body output. A requested filename is never reflected into these headers.
Content-Disposition's filename is advisory to a recipient, not a universal guarantee about what every browser saves. Likewise, HTTP caching directives express the intended storage policy; no-store alone does not certify privacy or prove an actual CDN configuration.
HEAD receives the accepted file metadata without calling fpassthru(). GET uses fpassthru on the already-open stream. The returned count is compared with the expected local copy size. It is not proof that a remote person received or retained a file, nor a whole-pipeline constant-memory or immediate-delivery guarantee.
If a copy is incomplete after commitment, the result cannot be withdrawn. The emitter returns a closed local outcome instead of appending an HTML/JSON diagnostic to the download. The caller must not print that outcome into the same response. The fixture did not inject a mid-stream copy failure or test recovery after an already-committed header block.
Use the following adapter only inside the private fixture
Create public/index.php with this complete test adapter. Its case routes select synthetic principals so the ownership outcomes can be reproduced; selecting a route is not login. It fails closed unless running under the controlled CLI-server setup with the freshly generated fixture marker.
<?php
declare(strict_types=1);
// PRIVATE TEST ADAPTER ONLY. Refuse outside the owned CLI-server/token setup.
$token = getenv('ML_DOWNLOAD_FIXTURE_TOKEN');
if (PHP_SAPI !== 'cli-server' || !is_string($token) || preg_match('/\A[a-f0-9]{32}\z/', $token) !== 1) {
http_response_code(503);header('Content-Type: text/plain; charset=UTF-8');header('Content-Length: 0');return;
}
require dirname(__DIR__) . '/private-download.php';
// Case routes select synthetic principals, NOT HTTP authentication.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/_fixture-ready') {
header('Content-Type: text/plain; charset=UTF-8');echo 'fixture-ready:' . $token;return;
}
$alice = ['id' => 'member-a', 'role' => 'member'];$bob = ['id' => 'member-b', 'role' => 'member'];
$cases = ['/binary' => [$alice, 'alpha'], '/empty' => [$alice, 'empty'], '/other-owner' => [$bob, 'beta'],
'/denied' => [$bob, 'alpha'], '/anonymous' => [null, 'alpha'], '/unknown-actor' => [['id' => 'member-c', 'role' => 'member'], 'alpha'],
'/missing' => [$alice, 'missing']];
[$actor, $id] = $cases[$path] ?? [null, 'missing'];
$private = dirname(__DIR__) . '/private';
$documents = ['alpha' => ['owner' => 'member-a', 'path' => $private . '/alpha.bin', 'bytes' => 10],
'empty' => ['owner' => 'member-a', 'path' => $private . '/empty.bin', 'bytes' => 0],
'beta' => ['owner' => 'member-b', 'path' => $private . '/beta.bin', 'bytes' => 12]];
$response = privateDownloadResponse($actor, $_SERVER['REQUEST_METHOD'], $id, $documents);
$held = $response['stream'];$opened = is_resource($held);
$outcome = emitPrivateDownload($response);
// Synthetic proof only: this private ledger is never emitted as download bytes.
$row = json_encode(['path' => $path, 'method' => $_SERVER['REQUEST_METHOD'], 'status' => $response['status'],
'opened' => $opened, 'closed' => $opened ? !is_resource($held) : null, 'copy' => $outcome], JSON_THROW_ON_ERROR) . "\n";
$ledger = $private . '/receipt.ndjson';
if (file_put_contents($ledger, $row, FILE_APPEND | LOCK_EX) !== strlen($row)) { exit(1); }
// No content after emission: errors must not become appended HTML or JSON.
Do not deploy those case routes as authentication. Real integration must replace that test identity selection with the application's independently verified identity and entitlement boundary. The core function still receives a server-owned actor and map, rather than trusting a posted identity or a requested filesystem location.
The checker below creates a new temporary root, copies these exact module/adapter bytes, and places private/ beside public/. It never requests a private file path directly or supplies traversal/exploit inputs. Its receipt ledger is private test evidence and is never part of the response body.
The ledger's opened field records whether the constructor returned a stream. It is not a kernel file-open trace. Source review establishes the authorization-before-I/O order; the request checks establish the declared returned-handle, header and byte outcomes.
Copy and run the complete original checker
Save this as check.php beside private-download.php, with the test adapter at public/index.php. These three inline blocks are the entire reproduction source: no archive, repository download or missing helper is required.
Use an already-provisioned approved PHP CLI with built-in stream-socket support and proc_open; no separate ext-sockets extension, Composer package, database or Docker is needed. Run only where a private loopback test process is authorized:
php check.php
The checker creates only its own tiny synthetic fixtures, launches its own 127.0.0.1 development server and stops it afterward. PHP's built-in server is for controlled development/testing, not a public production server. Its temporary child-only display_errors=0 flag changes no installed production configuration.
<?php
declare(strict_types=1);
require __DIR__ . '/private-download.php';
$checks=[];
function check(bool $ok,string $name): void {
global $checks;
if (!$ok) { throw new RuntimeException('FAILED: '.$name); }
$checks[]=$name;
}
function requestFixture(int $port,string $path,string $method): array {
$socket=stream_socket_client('tcp://127.0.0.1:'.$port,$errno,$error,1);
if ($socket===false) { throw new RuntimeException('loopback_connect'); }
try {
stream_set_timeout($socket,2);
$request="$method $path HTTP/1.1\r\nHost: 127.0.0.1:$port\r\nConnection: close\r\n\r\n";
if (fwrite($socket,$request)!==strlen($request)) { throw new RuntimeException('loopback_request_write'); }
$raw='';
while (!feof($socket)) {
$chunk=fread($socket,4096);
if ($chunk===false) { throw new RuntimeException('loopback_read'); }
$raw.=$chunk;
if (strlen($raw)>16384 || stream_get_meta_data($socket)['timed_out']) { throw new RuntimeException('loopback_response_bound'); }
}
} finally { fclose($socket); }
$parts=explode("\r\n\r\n",$raw,2);
if (count($parts)!==2) { throw new RuntimeException('loopback_header_boundary'); }
$lines=explode("\r\n",$parts[0]);$status=array_shift($lines);
if (!preg_match('/^HTTP\/1\.[01] ([0-9]{3}) /',$status,$match)) { throw new RuntimeException('loopback_status'); }
$headers=[];
foreach ($lines as $line) {
$pair=explode(':',$line,2);
if (count($pair)!==2) { throw new RuntimeException('loopback_header'); }
$key=strtolower($pair[0]);
if (array_key_exists($key,$headers)) { throw new RuntimeException('loopback_duplicate_header'); }
$headers[$key]=trim($pair[1]);
}
return ['status'=>(int)$match[1],'headers'=>$headers,'body'=>$parts[1]];
}
$root=null;$process=null;$log=null;$port=null;$pid=null;$argv=[];$wire=[];$ledger=[];$error=false;$stage='setup';
$cleanup=['child_started'=>false,'child_stopped'=>true,'port_closed'=>true,'owned_files_removed'=>false];
$binary="\x00\x01NOTES\r\n\xFF";$other="Other notes\n";$serverLog='';
try {
$token=bin2hex(random_bytes(16));$root=sys_get_temp_dir().'/ml-download-'.$token;
if (!mkdir($root,0700) || !mkdir($root.'/public',0700) || !mkdir($root.'/private',0700)) { throw new RuntimeException('fixture_directory'); }
foreach (['alpha.bin'=>$binary,'empty.bin'=>'','beta.bin'=>$other,'receipt.ndjson'=>''] as $name=>$bytes) {
if (file_put_contents($root.'/private/'.$name,$bytes)!==strlen($bytes)) { throw new RuntimeException('fixture_write'); }
}
foreach (['private-download.php','public/index.php'] as $name) {
if (!copy(__DIR__.'/'.$name,$root.'/'.$name) || hash_file('sha256',__DIR__.'/'.$name)!==hash_file('sha256',$root.'/'.$name)) {
throw new RuntimeException('fixture_source_copy');
}
}
$alice=['id'=>'member-a','role'=>'member'];$bob=['id'=>'member-b','role'=>'member'];
$map=['alpha'=>['owner'=>'member-a','path'=>$root.'/private/alpha.bin','bytes'=>10],
'empty'=>['owner'=>'member-a','path'=>$root.'/private/empty.bin','bytes'=>0],
'beta'=>['owner'=>'member-b','path'=>$root.'/private/beta.bin','bytes'=>12]];
foreach ([['GET','alpha',10,true],['HEAD','alpha',10,false],['GET','empty',0,true]] as [$method,$id,$length,$send]) {
$response=privateDownloadResponse($alice,$method,$id,$map);$handle=$response['stream'];
try { check($response['status']===200 && $response['length']===$length && $response['send_body']===$send && is_resource($handle) && ftell($handle)===0,$method.' '.$id.': accepted fixed mapped stream, no body read during preparation'); }
finally { if (is_resource($handle)) { fclose($handle); } }
check(!is_resource($handle),$method.' '.$id.': caller closes prepared handle');
}
$refusal=['status'=>404,'length'=>0,'stream'=>null,'send_body'=>false];
foreach ([[$bob,'alpha'],[null,'alpha'],[['id'=>'member-c','role'=>'member'],'alpha'],[$alice,'missing'],[$alice,''],[['id'=>1],'alpha']] as $i=>[$actor,$id]) {
check(privateDownloadResponse($actor,'GET',$id,$map)===$refusal,'generic refusal returns no handle/length case '.$i);
}
check(privateDownloadResponse($alice,'POST','alpha',$map)===array_replace($refusal,['status'=>405]),'unsupported method refused before file work');
$changedMap=$map;$changedMap['alpha']['bytes']=11;
check(privateDownloadResponse($alice,'GET','alpha',$changedMap)===array_replace($refusal,['status'=>500]),'unexpected observed source length fails closed');
$response=privateDownloadResponse($bob,'GET','beta',$map);$handle=$response['stream'];
try { check($response['status']===200 && $response['length']===12 && is_resource($handle),'same-role second actor may access its own fixed document'); }
finally { if (is_resource($handle)) { fclose($handle); } }
check(!is_resource($handle),'second owner caller closes prepared handle');
$stage='server';$reservation=stream_socket_server('tcp://127.0.0.1:0',$errno,$message);
if ($reservation===false) { throw new RuntimeException('fixture_port'); }
$name=stream_socket_get_name($reservation,false);$port=(int)substr($name,strrpos($name,':')+1);fclose($reservation);
$log=tmpfile();if ($log===false) { throw new RuntimeException('fixture_log'); }
$argv=[PHP_BINARY,'-d','display_errors=0','-S','127.0.0.1:'.$port,'-t',$root.'/public',$root.'/public/index.php'];
$environment=['ML_DOWNLOAD_FIXTURE_TOKEN'=>$token];$loader=getenv('LD_LIBRARY_PATH');
if ($loader!==false) { $environment['LD_LIBRARY_PATH']=$loader; }
$process=proc_open($argv,[0=>['pipe','r'],1=>$log,2=>$log],$pipes,$root,$environment);
if (!is_resource($process)) { throw new RuntimeException('fixture_server_start'); }
$cleanup['child_started']=true;$cleanup['child_stopped']=false;fclose($pipes[0]);$pid=proc_get_status($process)['pid'];
$deadline=microtime(true)+5;$ready=false;
while (microtime(true)<$deadline) {
if (!proc_get_status($process)['running']) { throw new RuntimeException('owned_child_exited'); }
set_error_handler(static fn()=>true,E_WARNING);
try { $probe=stream_socket_client('tcp://127.0.0.1:'.$port,$errno,$message,0.1); }
finally { restore_error_handler(); }
if ($probe!==false) {
fclose($probe);$reply=requestFixture($port,'/_fixture-ready','GET');
if ($reply['status']!==200 || $reply['body']!=='fixture-ready:'.$token) { throw new RuntimeException('fixture_identity'); }
$ready=true;break;
}
usleep(20000);
}
check($ready,'owned child readiness token on loopback');
$cases=[['GET','/binary',200,10,$binary],['HEAD','/binary',200,10,''],['GET','/empty',200,0,''],
['HEAD','/empty',200,0,''],['GET','/other-owner',200,12,$other]];
foreach (['/denied','/anonymous','/unknown-actor','/missing'] as $path) {
foreach (['GET','HEAD'] as $method) { $cases[]=[$method,$path,404,0,'']; }
}
foreach ($cases as [$method,$path,$status,$length,$expected]) {
$stage=$method.' '.$path;$response=requestFixture($port,$path,$method);$headers=$response['headers'];
check($response['status']===$status,$stage.': actual status');
$expectedType=$status===200?'application/octet-stream':'text/plain; charset=UTF-8';
check(($headers['content-type']??'')===$expectedType && ($headers['cache-control']??'')==='private, no-store' && ($headers['content-length']??'')===(string)$length,$stage.': exact type/cache/length headers');
check($status===200?($headers['content-disposition']??'')==='attachment; filename="document.bin"':!array_key_exists('content-disposition',$headers),$stage.': fixed authorized disposition or no private disposition');
check($response['body']===$expected && hash('sha256',$response['body'])===hash('sha256',$expected),$stage.': exact binary/empty body hash');
$wire[]=['method'=>$method,'path'=>$path,'status'=>$response['status'],'headers'=>$headers,'body_bytes'=>strlen($response['body']),
'body_sha256'=>hash('sha256',$response['body']),'body_base64'=>base64_encode($response['body'])];
}
$lines=file($root.'/private/receipt.ndjson',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
if ($lines===false) { throw new RuntimeException('fixture_ledger'); }
$ledger=array_map(static fn(string $line):array=>json_decode($line,true,8,JSON_THROW_ON_ERROR),$lines);
check(count($ledger)===count($cases),'one private emission receipt per functional request');
foreach ($ledger as $i=>$row) {
[$method,$path,$status,$length,$expected]=$cases[$i];
check($row['method']===$method && $row['path']===$path && $row['status']===$status && $row['copy']['complete']
&& $row['copy']['copied_bytes']===strlen($expected)
&& ($status===200?($row['opened'] && $row['closed']):(!$row['opened'] && $row['closed']===null)),
$method.' '.$path.': local copy result and returned-handle ownership');
}
$stage='complete';
} catch (Throwable $_caught) { $error=true; }
finally {
if (is_resource($process)) {
$state=proc_get_status($process);
if ($state['running']) {
proc_terminate($process,15);$deadline=microtime(true)+3;
do { usleep(20000);$state=proc_get_status($process); } while ($state['running'] && microtime(true)<$deadline);
}
$cleanup['child_stopped']=!$state['running'];
if ($cleanup['child_stopped']) { $cleanup['proc_close_exit']=proc_close($process); }
}
if ($port!==null) {
set_error_handler(static fn()=>true,E_WARNING);
try { $probe=stream_socket_client('tcp://127.0.0.1:'.$port,$errno,$message,0.2); }
finally { restore_error_handler(); }
$cleanup['port_closed']=$probe===false;if (is_resource($probe)) { fclose($probe); }
}
if (is_resource($log)) { rewind($log);$serverLog=stream_get_contents($log);fclose($log); }
if ($root!==null && $cleanup['child_stopped']) {
$removed=true;
foreach (['public/index.php','private-download.php','private/alpha.bin','private/empty.bin','private/beta.bin','private/receipt.ndjson'] as $name) {
if (is_file($root.'/'.$name) && !unlink($root.'/'.$name)) { $removed=false; }
}
foreach (['public','private'] as $name) { if (is_dir($root.'/'.$name) && !rmdir($root.'/'.$name)) { $removed=false; } }
$cleanup['owned_files_removed']=$removed && rmdir($root);
}
}
$passed=!$error && $cleanup['child_stopped'] && $cleanup['port_closed'] && $cleanup['owned_files_removed'];
echo json_encode(['status'=>$passed?'passed':'failed','stage'=>$stage,'PHP'=>PHP_VERSION,'checks'=>$checks,'wire'=>$wire,'ledger'=>$ledger,
'private_fixture_total_bytes'=>strlen($binary)+strlen($other),'owned_server'=>['pid'=>$pid,'argv'=>$argv,'port'=>$port,
'environment_keys'=>array_keys($environment??[])],'cleanup'=>$cleanup,'server_log'=>$serverLog,
'limits'=>'Synthetic trusted principals only, not HTTP authentication. Source ordering establishes authorization before document I/O; receipt opened records returned handles, not a kernel-open trace. No CDN/cache/TLS/browser receipt/Range/concurrent-mutation/production security guarantee.'],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR),"\n";
exit($passed?0:1);
Interpret the observed result within its boundary
All three sources linted, and the first actual run returned clean JSON with 83 checks, exit zero and empty stderr. The 13 functional wire cases covered binary GET/HEAD, empty-file GET/HEAD, the second owner's accepted GET, and GET/HEAD refusals for the other owner, anonymous actor, unknown actor and missing document.
Accepted headers matched exactly, including Content-Length; GET body bytes and SHA256 matched the known synthetic bytes. Authorized HEAD had the same intended file length but no body. Refused responses were empty with generic type, zero length and no Content-Disposition. The pure logic checks also exercised unsupported-method refusal and an unexpected source-length mismatch.
The owned server stopped, its port closed, and the exact fixture files/directories were removed. proc_close() returned -1 after the child was already observed exited; that value is retained rather than called child exit zero. Abrupt interruption cleanup and other platforms were not tested.
No real login/session correctness, server/CDN cache behavior, TLS delivery, resumable Range requests, arbitrary filesystem mutation or full-site security follows from those cases. Receiving uploads is a different boundary, covered by the PHP upload guide. WishList Member paid-download protection addresses a separate product/server setup rather than this plain-PHP byte-delivery fixture.
For help reviewing the actual identity, storage and response boundary in an existing application, see the development services.