0

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

现在我正在尝试建立一个 download.php 文件,当打开带有 uniqid 的特定链接时,脚本在数据库中查找搜索 uniqid 的文件并显示针对它的信息。

这是我的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;
?>

请先告诉我应该创建什么样的链接。localhost/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;
?>
4

1 回答 1

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

于 2013-09-04T12:52:31.397 回答