Downloading files from MySQL database using PHP

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Locked
vthokie11
Forum Newbie
Posts: 2
Joined: Tue Jul 12, 2011 3:43 pm

Downloading files from MySQL database using PHP

Post by vthokie11 »

Hi,

I have several files stored in a database and I have a script to download those files. Everything works great with plain text files but with anything else (pdf, jpeg, doc, etc...) I just get a lot of junk. I'm guessing its showing me the plain text version of a file that is encoded to open with an application. I am including the script I am using to get the files....any help would be greatly appreciated.

Code: Select all

<?php
if(isset($_GET['id']))
{
// connect to the database
include "connect.php";

// query the server for the file
$id = $_GET['id'];
$query = "SELECT * FROM upload WHERE id = '$id'";
$result  = mysql_query($query) or die(mysql_error());

// define results into variables
$name=mysql_result($result,0,"name");
$size=mysql_result($result,0,"size");
$type=mysql_result($result,0,"type");
$content=mysql_result($result,0,"content");

header("Content-disposition: attachment; filename=$name");
header("Content-length: $size");
header("Content-type: $type");
echo $content;

mysql_close();
}
else{
die("No file ID given...");
}

?> 

vthokie11
Forum Newbie
Posts: 2
Joined: Tue Jul 12, 2011 3:43 pm

Re: Downloading files from MySQL database using PHP

Post by vthokie11 »

I guess you may need to know how they are stored in the database...the following is the script used to store the files:

Code: Select all

<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}

include 'connect.php';

$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

mysql_query($query) or die('Error, query failed');

echo "<br>File $fileName uploaded<br>";
}
?>
untz
Forum Newbie
Posts: 4
Joined: Wed Jan 20, 2016 3:53 am

Re: Downloading files from MySQL database using PHP

Post by untz »

hi, i try to use your code, to download a file, but when i try to do a download, i download a file name index.php, no the file i want, so if you can help me i will appreciate it

thank you :)
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Downloading files from MySQL database using PHP

Post by Celauran »

This is a post from five years ago. Start a new thread if you need to.
Locked