faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

10 of 12 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Is there a PHP way of allowing users to download zip files from my web server?

Aug 16th, 2002 17:09
Guest,


Yes. do this (simple... you can make it more complex):
-----// Being Code! //-----
<?php
if(!$_REQUEST['file']) exit('No filename specified');
$bin_root="C:\\Apache\\htdocs\\"; //Probably needs changing, also 
note, _NEEDS TRAILING SLASH!_
$illegals=array('.php');
$headers=array('.zip'=>'Content-Type: application/zip');
$file=$_REQUEST['file'];
$filename=basename($file);
$fileext=ereg_replace("^(.)+(\.(.){1,3})$",'\2',$filename);
$path=dirname($file);
if(in_array($fileext,$illegals)) exit('You are requesting a blocked 
file-type.');
if(!is_dir($bin_root.$path)) exit('Invalid path '.$path.' to 
file '.$filename);
if(!is_file($bin_root.$file)) exit('File not found.');
if(key_exists($fileext,$headers)) //"If this is a known extension" 
**** note: Before php 4.0.6 key_exists needs to be array_key_exists
header($headers[$fileext]);
else header('Content-type: application/octet-stream'); //Otherwise, 
give generic binary header.
header('Content-Disposition: attachment; filename='.$filename); //We 
want the download prompt to already know our filename, right?
readfile($bin_root.$file);
?>
-----// End code! //-----
I wrote that without checking it... there is probably a more efficient 
way of doing things. (I doubt it though :-))
That works pretty well... mabey I should be more careful about Dirs... 
but hey, I said it was quazi simple, right? :-)
--Nate
Email: [email protected]