Solved

Download a file

Posted on 2007-03-17
1
281 Views
Last Modified: 2008-03-06
I would like to create a download link to a file outside the web server area, for example in the /tmp/

I could create a list of the files, but I dont know how to make it downloadable.

So far, I can create this link :

<a href="get_file.php?file=$file> $file </a>

Anyone know how to code the "get_file.php" so it will download the $file?

The $file is not in the web server area, for example /tmp/test.txt

I tried it like this (see below), but it does not work:

<?php

  header("Content-type: application/octet-stream");
  header("Content-disposition: attachment; filename=$file");

  $file = $_REQUEST['file'];
 
  echo $file;
 
  if (substr($file,0,5) != '/tmp/') {
     readfile($file);
  } else {
     echo "Error reading file";
  }

?>


Thanks!
0
Comment
Question by:nova2002
1 Comment
 
LVL 49

Accepted Solution

by:
Roonaan earned 125 total points
ID: 18739659
<?php

  $file = $_REQUEST['file'];

  $file = str_replace('..', '', $file); //prevent people from entering ../../.htaccess or something

  $path = '/tmp/'. $file;

  if(is_file($file)) {
    header("Content-type: application/octet-stream");
    header("Content-disposition: attachment; filename=".basename($file));
     readfile($file);
  } else {
     echo "Error reading file";
  }
?>

Then make sure that you use a relative path as your get_file.php argument:
For /tmp/file1.pdf, it would be get_file.php?file=file1.pdf
For /tmp/sub/file2.pdf, it would be get_file.php?file=sub/file2.pdf

Hope this helps,

-r-
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question