Hello Friends ,

Once we upload file in Mysql database , we need to download file from Mysql database .
When we upload a file to MYSQL database we also save the file type and length.
These were not needed for uploading the files but is needed for downloading the files from the database.

Download page shows the list of file names stored in database. And it shows the download link as below. e.g. download.php?id=1

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Download files from MYSQL database</title>
</head>
<body>

<?php

$dbhostname = ‘localhost’;
$dbusername = ‘root’;
$dbpassword = ”;
$connection = mysql_connect($dbhostname, $dbusername, $dbpassword)
mysql_select_db(“testing”);

$sql = “SELECT id, name FROM tbl_upload”;
$res = mysql_query($sql);
if(mysql_num_rows($res) == 0)
{
echo “There is no uploaded files in database. <br />”;
}
else
{
while(list($id, $name) = mysql_fetch_array($res))
{
?>
<a href=”download.php?id=<?php echo $id;?>”><?php echo $name;?></a>
<?php
}
}
mysql_close($connection);

?>

</body>
</html>

When you click the download link, we can identify the file to get from mysql database using the id passed by GET method ($_GET['id']) . Below is the code for downloading files from MySQL Database.

<?php
if(isset($_GET['id']))
{
$dbhostname = ‘localhost’;
$dbusername = ‘root’;
$dbpassword = ”;
$connection = mysql_connect($dbhostname, $dbusername, $dbpassword)
mysql_select_db(“testing”);
$id    = $_GET['id'];

$sql = “SELECT name, type, size, content FROM tbl_upload WHERE id = ‘$id’”;
$res = mysql_query($sql);

list($name, $type, $size, $content) = mysql_fetch_array($result);
header(“Content-length: $size”);
header(“Content-type: $type”);
header(“Content-Disposition: attachment; filename=$name”);
echo $content;

mysql_close($connection);
exit;

}

?>

Before sending the file content using echo first we need to set several headers. They are :

header(“Content-length: $size”) : This header tells the browser how large the file is. it’s a good manner telling how big the file is. so anyone who download the file can predict how much time the download will take.

header(“Content-type: $type”) : This header tells the browser what kind of file it tries to download.

header(“Content-Disposition: attachment; filename=$name”) : Tells the browser to save this downloaded file under the specified name.

After sending the file the script stops executing by calling exit.

Cheers !!

No related posts.