« Monsters, Inc. | Main | blogChalking »

October 09, 2002

Download File CGI

I found this one from a post a while ago. This is a very nice script to have. It's a CGI script that you can use for downloading files. Basically, you can create a link with this script, which will go get the file and stream it to the user. It does it in a way that the filename will be passed to the user's save dialog. This is a great way to protect your content from deep linking and to control who is allowed to download which files (you would have to add code to check, of course).

Thanks to Tim Vattima for needing this.

Thanks to Matt Jadud for his example

Special Note: This code is not a secure solution. It does have loop holes and I have not had time to fix them.

#!/usr/bin/perl
#
# Download a file through this CGI script
# Pass the filename down to the save dialog (nice!)
# Warning, this technique may have security implications
# author: Chris Tulino
#
# Thanks to Matt Jadud for his example:
# http://www.cs.indiana.edu/vincent/code/cgi/download.html
#

 use CGI;
 $query = new CGI;
 $redirect = "http://www.site.com/errorpage?msg=File not found.";
 $fileroot="/pub/files";
 local $| = 1;  # Do not buffer output

 if ($query->param) {
  $filename=$query->param("filename");
  $location=$query->param("location");
 } else {
  print $query->redirect($redirect);
 }

 $file=$fileroot . "/" . $location . "/" . $filename;

 unless -r $file {
  print $query->redirect($redirect);
 }

 # we now have a file we can read...begin transmission

 print "HTTP 200/OK\n";
 print "Content-Type: application/octet-stream\n";
 print "Content-Disposition: attachment; filename=$filename\n\n";
 sendfile($file);

 return 1;

 sub sendfile  {
  my($file);
  ($file) = @_;
  open (FILE, $file) || die("$file not found!");
  binmode(FILE);
  while (read FILE, $buffer, 1024) {
   print $buffer;
  }
  close(FILE);
 }

Posted by Chris at October 9, 2002 05:40 PM

Subscribe to this entry:   Email address:   

Trackback Pings

TrackBack URL for this entry:
http://www.christulino.com/cgi-bin/mt/mt-tb.cgi/27

Comments