Created
December 11, 2018 07:03
-
-
Save cleverinx/176b58796d1a3c1927dd1b121b5e40c1 to your computer and use it in GitHub Desktop.
Simple PHP script to allow downloading a file only once, after which it is deleted or renamed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ($_POST["submit"]) { | |
$file_name = '/srv/users/path/to/filename.zip'; | |
// make sure it's a file | |
if (is_file($file_name)) { | |
// required for IE | |
if (ini_get('zlib.output_compression')) { | |
ini_set('zlib.output_compression', 'Off'); | |
} | |
// get the file mime type using the file extension | |
switch (strtolower(substr(strrchr($file_name, '.'), 1))) { | |
case 'pdf': $mime = 'application/pdf'; break; | |
case 'zip': $mime = 'application/zip'; break; | |
case 'jpeg': | |
case 'jpg': $mime = 'image/jpg'; break; | |
default: $mime = 'application/force-download'; | |
} | |
header('Pragma: public'); // required | |
header('Expires: 0'); // no cache | |
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); | |
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file_name)).' GMT'); | |
header('Cache-Control: private', false); | |
header('Content-Type: '.$mime); | |
header('Content-Disposition: attachment; filename="'.basename($file_name).'"'); | |
header('Content-Transfer-Encoding: binary'); | |
header('Content-Length: '.filesize($file_name)); // provide file size | |
header('Connection: close'); | |
readfile($file_name); // push it out | |
unlink("/srv/users/path/to/filename.zip"); | |
// rename("/srv/users/path/to/filename.zip", "/srv/users/path/to/filename-donloaded.zip"); | |
// optionally rename file instead of deleting | |
exit(); | |
} | |
} | |
?> | |
<form action="" method="POST"> | |
<a class="btn" href="http://yoursite.com/filename.zip" download> | |
<input type="submit" name="submit" value="Download This File"> | |
</a> | |
</form> | |
<style> | |
input{ | |
background: #673AB7; | |
color: #fff; | |
padding: 20px; | |
font-size: 15px; | |
cursor:pointer; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment