download file dari mysql dengan PHP

kemarin telah saya post yang upload, dan sekarang saya ingin menampilkan dan mengambil file tersebut. menggunakan database kemarin, berikut source tampilannya.

<?php
$db_host = 'localhost'; // don't forget to change
$db_user = 'root';
$db_pwd = '';
$database = 'uts';
$table = 'transaksi';

if (!mysql_connect($db_host, $db_user, $db_pwd))
  die("Can't connect to database");
if (!mysql_select_db($database))
  die("Can't select database");

$result = mysql_query("SELECT id_file, nm_file, id_dosen, type_file, des_file from transaksi");

if(mysql_num_rows($result) == 0)
{
echo "Database is empty
";
}
else
{
while(list($id, $nm_file, $nm_dosen, $type_file, $des_file) = mysql_fetch_row($result))
{
// outputing list
		echo "
<tr>";
		echo "
<td align='left' width='22%'>";
		echo "
	<li>";
		echo "<a href='download.php?show={$id}' target='_blank'>{$nm_file}</a> &ndash; ";
		echo "<small>{$des_file}</small> &ndash; ";
		echo "<small>{$nm_dosen}</small></li>
";
		echo "</td>
";
		echo "</tr>
";
}
}
?>

dan beirkut download.php

<?php
$db_host = 'localhost'; // don't forget to change
$db_user = 'root';
$db_pwd = '';
$database = 'uts';
$table = 'transaksi';

if (!mysql_connect($db_host, $db_user, $db_pwd))
  die("Can't connect to database");
if (!mysql_select_db($database))
  die("Can't select database");

$strID=$_GET&#91;'show'&#93;;

$result = mysql_query("SELECT id_file, nm_file, ext, id_dosen, type_file, size_file, isi_file, des_file from transaksi where id_file=$strID");

$row = mysql_fetch_array( $result );
if (!empty($row&#91;"isi_file"&#93;))
{
// Output the MIME header - Force as Octet Stream
// You could get this from the FileType Column
header("Content-type: application/octet-stream");
header("Content-Length: " . strlen($row&#91;'isi_file'&#93;) );
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$row&#91;'nm_file'&#93;.'.'.$row&#91;'ext'&#93;.'"');
header("Content-Transfer-Encoding: binary\n");
echo $row&#91;'isi_file'&#93;;
}
?>

ya, itu lah. Semoga bermanfaat 🙂

Leave a comment