当文件名从MySQL数据库引入时,PHP文件下载链接不起作用


PHP File Download Links Not Working when filenames brought in from MySQL Database

当下载链接是通过PHP从MySQL数据库创建的时,我很难让它们正常工作。用于获取文件名的代码如下(GET值用于测试;该值通常来自另一个网页):

$_GET[attachid] = '2597'; //Test value for getting filenames
if(isset($_GET[attachid]) && isset($_GET[UID])) 
  { 
   $attachid = $_GET[attachid];
   $uid = $_GET[UID];
   $sql = "SELECT name, type, size, content FROM requisitions.upload WHERE attachId
   ='$attachid'";                                                                                                                                                                                                                                                                                                                  
   $res = mysql_query($sql) or die(mysql_error());
   list($name, $type, $size, $content) = mysql_fetch_array($res);
   header("Content-length: $size");
   header("Content-type: $type");
   header("Content-Disposition: attachment; filename=$name");
   echo $content;
   exit; }
   ?>

接下来是基于attachid:从MySQL数据库生成文件名表的代码

<?php
$sql = "SELECT UID, attachId, name FROM requisitions.upload WHERE attachId = 
'$_GET[attachid]'";
$res6 = mysql_query($sql) or die(mysql_error());
$name = 'name';
$attachid = 'attachId';
$uid = 'UID';
while($row = mysql_fetch_array($res6, MYSQL_ASSOC))
 {
 ?>
  <tr>
<td>
    <?php echo $row['attachId']; ?>
    </td>  
   <td> 
  <?php echo "<a href=quotes.php?attachid={$row['attachId']}&uid={$row['UID']}>
  {$row['name']}</a></td>";
 } </tr></table>

上面生成了一个表,其中包含正确的attachid和文件名(在本例中为三个),每个文件名都显示为附加了attachiduid的链接,但当我单击链接时,什么都没有发生。我刚回到quotes.php,没有下载。知道我可能做错了什么吗?就好像没有人读标题一样。我在IIS 7上运行这个,如果有区别的话。

$_GET是一个带有命名键的关联数组。因此,在访问其成员时,您需要将密钥名称用引号括起来。

$_GET['attachid'] = '2597'; //Test value for getting filenames
if(isset($_GET['attachid']) && isset($_GET['uid'])) 
  { 
   $attachid = $_GET['attachid'];
   $uid = $_GET['uid'];
   $sql = "SELECT name, type, size, content FROM requisitions.upload WHERE attachId
   ='".$attachid."'";                                                                                                                                                                                                                                                                                                                  
   $res = mysql_query($sql) or die(mysql_error());
   list($name, $type, $size, $content) = mysql_fetch_array($res);
   header("Content-length: ".$size);
   header("Content-type: ".$type);
   header("Content-Disposition: attachment; filename=".$name);
   echo $content;
   exit; }
   ?>

请记住,您的代码目前完全容易受到SQL注入攻击,mysql_*已被弃用。强烈建议使用PDO/prepared语句。在数据库中使用$_GET变量之前,至少要对其进行转义。

编辑:在将变量名作为字符串的一部分添加之前,还需要将变量连接到标题中。请参阅上面的代码块。