Could use some help downloading a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kristolklp
Forum Commoner
Posts: 30
Joined: Mon Sep 05, 2005 2:24 pm

Could use some help downloading a file

Post by kristolklp »

I have a function setup to download an image file from a database, however i have decided to store my images in a directory on the server instead due to size limitations of the database. I am trying to modify my function to downlaod the file from the directory but I can't seem to get it work.

Here is the simplified code for downlaoding from the db:

Code: Select all

case 'dl':

$sql = "SELECT * FROM ".$table." WHERE image_id=".$iid;
$result = mysql_query($sql,$conn);
if (mysql_num_rows ($result)>0) {
$row = @mysql_fetch_array($result);

$filename = $row["image_name"];
$file = $row["image_path"];
$file_type = $row["image_type"];
$file_size= $row["image_size"];

if(!$file){ 
echo "ERROR: No image to download."; 
} else { 

  header("Content-type: $image_type");
  header("Content-length: $image_size");
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-Description: PHP Generated Data");
  echo $file;

exit();
}
}
break;
Now instead of saving the binary image in the database I am saving it to a directory on my server "/uploads". The only line of code I am changing is the "$file=" line but it just displaying the image instead of downloading. How do I get it to download instead? The image path is stored in the database.

Code: Select all

$file= readfile("http://".$_SERVER['HTTP_HOST'].$row["image_path"]);
Thanks for any help!
kristolklp
Forum Commoner
Posts: 30
Joined: Mon Sep 05, 2005 2:24 pm

Post by kristolklp »

finally figured it out!

Code: Select all

case 'dl':

$sql = "SELECT * FROM ".$table." WHERE image_id=".$iid;

$result = mysql_query($sql,$conn);
if (mysql_num_rows ($result)>0) {
$row = @mysql_fetch_array($result);

$file = $row["image"];
$filename = $row["image_name"];
$file_type = $row["image_type"];
$file_size= $row["image_size"];

if(!$file){ 
echo "ERROR: No image to download. Please try again."; 
} else { 

  header("Content-type: $image_type");
  header("Content-length: $image_size");
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-Description: PHP Generated Data");
  readfile ($file);

exit();
}
}
break;
Post Reply