1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| <?
// Sample usage
function sendTest()
{
$res = sendFile('application.exe', 'application/octet-stream');
if ($res['status']) {
// Download succeeded
} else {
// Download failed
}
@saveDownloadStatus($res);
}
// The sendFile function streams the file and checks if the
// connection was aborted.
function sendFile($path, $contentType = 'application/octet-stream')
{
ignore_user_abort(true);
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="' .
basename($path) . "\";");
header("Content-Type: $contentType");
$res = array(
'status' =false,
'errors' =array(),
'readfileStatus' =null,
'aborted' =false
);
$res['readfileStatus'] = readfile($path);
if ($res['readfileStatus'] === false) {
$res['errors'][] = 'readfile failed.';
$res['status'] = false;
}
if (connection_aborted()) {
$res['errors'][] = 'Connection aborted.';
$res['aborted'] = true;
$res['status'] = false;
}
return $res;
}
// Save the status of the download to some place
function saveDownloadStatus($res)
{
$ok = false;
$fh = fopen('download-status-' . $_SERVER['REMOTE_ADDR'] . '-' .
date('Ymd_His'), 'w');
if ($fh) {
$ok = true;
if (!fwrite($fh, var_export($res, true))) {
$ok = false;
}
if (!fclose($fh)) {
$ok = false;
}
}
return $ok;
} |
Partager