如何在数据库中创建文件的下载链接

时间:2013-09-04 12:23:21

标签: php

我创建了一个上传表单和一个php文件,它提取文件的名称,大小,类型,并将其存储在表格文件中的数据库上载脚本中。该文件还有一个uniqid,它也存储在同一个表中。

现在我正在尝试构建一个download.php文件,我希望在打开uniqid的特定链接时,脚本会在数据库中查找搜索uniqid的文件并显示相关信息。?< / p>

这是我的upload.php

<?php
include('config.php');

function bytesToSize1024($bytes, $precision = 300) {
    $unit = array('B','KB','MB');
    return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}
$FileName = $_FILES['filename']['name'];
$FileType = $_FILES['filename']['type'];
$FileSize = bytesToSize1024($_FILES['filename']['size'], 1);
$Fileid = uniqid(rand());
$tmp_name = $_FILES["filename"]["tmp_name"];
if ($_FILES["filename"]["error"] > 0)
   {
   echo "Apologies, an error has occurred.";
   echo "Error Code: " . $_FILES["fileToUpload"]["error"];
   }
else
   {

   move_uploaded_file($_FILES["filename"]["tmp_name"],
  "C:\wamp\www\upload\upload" . $_FILES["filename"]["name"]);
}
$query2 = "INSERT INTO files (id, name, size, type) VALUES ('$Fileid', '$FileName', '$FileSize', '$FileType')";
    $result2 = mysql_query($query2);
echo <<<EOF
<p>Your file: {$FileName} has been successfully received.</p>
<p>Type: {$FileType}</p>
<p>Size: {$FileSize}</p>
<p>Temp Foler: {$tmp_name}</p>
<p>Download Link: localhost/upload/download.php?=$Fileid

EOF;
?>

请先告诉我应该创建哪种类型的链接。本地主机/的download.php?= uniqid

以上示例将如何工作以及如何使其工作。我很困惑?

这里我试图创建一个download.php文件,但它不是很好

<?php
include('config.php');
$query = "SELECT * FROM files";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
?>
<?php
echo <<<EOF
File Name: <?php echo $row['name']; ?>
$row

EOF;
?>

1 个答案:

答案 0 :(得分:0)

这是您需要的代码。考虑在数据库中存储字节数以获取文件大小。 当然,可能需要进行一些更改才能完全符合您的要求。

<?php
    include('config.php');
    //get id from GET method and make sure that it's safe to be used in the query
    $id=mysql_real_escape_string($_GET['id']);
    $query = "SELECT * FROM `files` WHERE `id`='$id'";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    if (count($row)!=1)    //check if our unique record has been found
        die('Sorry but we could not find this file!');
    $row=$row[0];

    //send download headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$row['name']);
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: no-cache');
    header('Content-Length: ' .$row['size']);

    readfile(upload" . $row['name']);   //I recommend you to change the path and file name of your uploaded files!
?>

链接示例:http://yourdomain.com/download.php?id=123