How can I let download my file ?

By admin at 9 July, 2008, 9:57 am

Normally, Downloading is the process of taking a file from a computer on the Internet and saving that file on your computer. Are you searching for the PHP source code for downloading the file? Then, you are at the right place. Here is a simple PHP code, that let the file to download; you have uploaded. So, without delaying a second lets start to do our work.

——–
Firstly, create the download form that allows one to download the file.
——–
[download_form.php]

1
2
3
4
5
6
7
8
9
10
11
 
<?php
 
##################################
#Copyright 2008, Jayesh Shrestha
#You may use, modify and distribute  
#this code as long as this copyright
# notice is preserved.
##################################
 
?>
1
2
3
4
 
<!-- form for download -->
 
<form name="download" action="download.php" method="post">
1
2
3
4
5
6
 
<?php 
 
$safeFilename = '/^\w+\.\w+$/'; 
$downloads = "download-dir/";
?>
1
<select name="filename">
1
2
3
4
5
6
7
8
9
10
  <?php
 
  $dir = opendir($downloads);
  if (!$dir) {
    die("Bad downloads setting");
  }
  while (($file = readdir($dir)) !== false) {
    // List only files with a safe filename
    if (preg_match($safeFilename, $file)) {
?>
1
  <option value="<?php echo $file?>"><?php echo $file?></option>
1
2
3
4
5
  <?php
   }
  }
  closedir($dir);
?>
1
2
3
</select>
<input type="submit" name="download" value="Download">
</form>

——–
NOTE :: Place the files in the directory named (download_dir).
——–

[download.php]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
<?php
 
##################################
#Copyright 2008, Jayesh Shrestha
#You may use, modify and distribute  
#this code as long as this copyright
# notice is preserved.
##################################
 
if(isset($_POST['download']))
{
  $filename = $_POST['filename'];
 
  $downloads = "download-dir/$filename";
 
  // Now make sure the file actually exists
 
  if (!file_exists("$downloads")) {
 
	echo "<h1>File does not exist</h1>";
 
  } //end of if 1.1
  else
  {
	  header("Content-disposition: attachment; filename=$filename");
	  header("Content-type: application/octet-stream");
	  readfile("$downloads");
	  exit(0); 
 
  }//end of else
 
} //end of if 1
 
?>

To download a file, one generally needs to select file and click Download button , which automatically starts the download process. After starting the download, a dialog box will prompt the user to choose a place to download the file. This download location can be on the user’s hard-drive or a floppy disk. After choosing a location and clicking OK, the file will begin to download.


Spread the Words!




No comments yet.

Sorry, the comment form is closed at this time.