You are here
Home > Web Development > PHP Development > How to create file download script in php ?

How to create file download script in php ?

This PHP script works on Apache web servers for all kind of files bigger than 500MB from a password protected directory. The cache control header is used to force the download for text files and other files even if they are opened by default inside your web browser.

Step 1. Create a PHP script, name it “download.php” and copy/paste the following code:


set_time_limit(0); // disable the time limit for this script

$path = “/absolute_path_to_your_files/”; // change the path to fit your websites document structure

$dl_file = preg_replace(“([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})”, ”, $_GET[‘download_file’]); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;

if ($fd = fopen ($fullPath, “r”)) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts[“extension”]);
switch ($ext) {
case “pdf”:
header(“Content-type: application/pdf”);
header(“Content-Disposition: attachment; filename=\””.$path_parts[“basename”].”\””); // use ‘attachment’ to force a file download
// add more headers for other content types here
header(“Content-type: application/octet-stream”);
header(“Content-Disposition: filename=\””.$path_parts[“basename”].”\””);
header(“Content-length: $fsize”);
header(“Cache-control: private”); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
fclose ($fd);

Step 2. Create on your webpage links for each file which resists in a password protected directory or in a directory above the website root directory. Use for our example the following download URL:

<a href="">PHP download file name</a>

Leave a Reply