【问题标题】:Download link doesn't generate when I select a file from database当我从数据库中选择文件时,不会生成下载链接
【发布时间】:2015-03-01 17:46:07
【问题描述】:

我尝试生成一个链接以便从我的数据库中下载文件。我首先从下拉列表中选择一个文件,然后它会将您定向到另一个页面,并在该页面中创建您的链接,但是当我想这样做时,如果我单击下载文件,它会返回上一页蚂蚁它不会创建一个链接。
这是我的下载.php:

<html>
<body>
<title>Download your friend's uploads</title>
<form action="download2.php" method="post">
 <?php
session_start();
$username =$_SESSION["uname"];
?>

<?php
$con = mysqli_connect("localhost", "root", "", "webpage");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= mysqli_query($con, "SELECT imagesnotes FROM userdata where sharedpeople='$username'");
echo "File or Image";

echo'<select name="imagesnotes">';
echo'<option value="" selected="selected">Select a File</option>';

while($row = mysqli_fetch_array($sql))

{
    echo'<option value="' . $row['imagesnotes'] . '">'. $row['imagesnotes'] .'</option>';
}
echo'</select></p><p>';

mysqli_close($con);
 ?>
 <td width="80"><input name="download" type="submit" class="box" id="download" value=" download "></td>
</form>
</body>
</html>

用户从那里选择一张图片并点击提交按钮。


这是我的download2.php:

<?php
session_start();
$username =$_SESSION["uname"];
?>

<?php

 $con = mysqli_connect("localhost", "root", "", "webpage");
 if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $imagesnotes = $_POST['imagesnotes'];

 $query = "SELECT imagesnotes From userdata where imagesnotes='$imagesnotes' and sharedpeople='$username'";
 $res = mysqli_query($con,$query);
 $res or die('Error, query failed');
 if(mysqli_num_rows($res) == 0){
 echo "<br>Database is empty </br>";
 } 
 else{
 while(list($id) = mysqli_fetch_array($res)){
?>

 <br><a href="download.php?id=<?php=$id;?>">download your file</a></br>
 <?php
 }
 }

 mysqli_close($con);

?>

在这里,它必须创建一个链接来下载文件。我做错了什么?你能帮我吗?谢谢。

更新:


所以我的upload2.php最终版本是这样的:

<?php
session_start();
$username =$_SESSION["uname"];
?>
<?php 
if(isset($_GET['imagesnotes'])) 
{
// if id is set then get the file with the id from database
$con = mysqli_connect("localhost", "root", "", "webpage");
 if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$id    = $_GET['imagesnotes'];
$query = "SELECT imagesnotes, type, size, content FROM datas WHERE imagesnotes = '$id'";

$result = mysqli_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysqli_fetch_array($result);

header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;

mysqli_close($con);
}
?>

<?php

 $con = mysqli_connect("localhost", "root", "", "webpage");
 if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $imagesnotes = $_POST['imagesnotes'];

 $query = "SELECT imagesnotes From userdata where imagesnotes='$imagesnotes' and sharedpeople='$username'";
 $res = mysqli_query($con,$query);
 $res or die('Error, query failed');
 if(mysqli_num_rows($res) == 0){
 echo "<br>Database is empty </br>";
 } 
 else{
 while(list($id) = mysqli_fetch_array($res)){
?>

 <br><a href="download.php?id=<?php echo $id;?>">download your file</a></br>
 <?php
 }
 }


 mysqli_close($con);

?>

但它仍然将我带到上一页。为什么会这样?
更新 2:所以当我下载文件时,我下载了损坏的文件。这是我的uploadfile.php:

<html>
<body>
<?php
session_start();
$username =$_SESSION["uname"];
?>
<title>Uploading Page</title>
<b>Hello again,<?php echo $username ?>. From here, you can select your image or file and upload our database.</b>
<form method="post" action ="uploaded.php" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</body>
</html>


这是我上传的.php,用于确认更新操作:

<html>
<body>
<title>Uploading Page</title>

<?php
session_start();
$username =$_SESSION["uname"];
?>
<?php
$con=mysqli_connect("localhost","root","","webpage");
if (mysqli_connect_errno()) 
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}

$query = "INSERT INTO datas (username,imagesnotes,size,type,content) ".
"VALUES ('$username','$fileName', '$fileSize', '$fileType', '$content')";

$res=mysqli_query($con,$query);
$res or die('Error, query failed'); 

echo "<br>File $fileName uploaded<br> <a href = 'default.php'>Return</a> ";
} 
mysqli_close($con);
?>
</body>
</html>

我做错了什么?谢谢。
更新 3:现在我将文件上传到服务器而不是数据库。但现在我有一个问题,我无法将该文件用于下载链接。我怎样才能做到这一点?
这是我下载的yours.php:

<html>
<body>
<title>Download your uploads</title>

<?php
session_start();
$username =$_SESSION["uname"];
?>
<form action="downloadyours2.php" method="post">

<?php
$con = mysqli_connect("localhost", "root", "", "webpage");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= mysqli_query($con, "SELECT imagesnotes FROM datas where username='$username'");
echo "File or Image";

echo'<select name="imagesnotes">';
echo'<option value="" selected="selected">Select a File</option>';

while($row = mysqli_fetch_array($sql))

{
    echo'<option value="' . $row['imagesnotes'] . '">'. $row['imagesnotes'] .'</option>';
}
echo'</select></p><p>';

mysqli_close($con);
 ?>
<td width="80"><input name="download" type="submit" class="box" id="download" value=" download "></td>
</form>
</body>
</html>

这是我下载的yours2.php:

<!DOCTYPE html>
<html>
<head>
<title>Your download link is ready</title>
</head>
<body>
<?php
    // No need to query the database again, you get the filename from POST data
 echo '<br /><a href="downloadedyours.php?imagesnotes=' . $_POST['imagesnotes'] . '">Download your file</a><br />';
 ?>
</body>
</html>

这是我下载的yours.php:

 <?php
session_start();
$username =$_SESSION["uname"];
?>
<?php
 if(isset($_GET['imagesnotes'])) 
    {
    $con = mysqli_connect("localhost", "root", "", "webpage");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $target_dir = "uploads/";
  $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $imagesnotes = $_GET['imagesnotes'];
        // Set database name
        $db = "webpage";
        // If $_GET['imagesnotes'] is set then get the file with that filename from database
        // Expecting a single result row: let's use mysqli_fetch_array(query(...), MYSQLI_ASSOC) function
        $sql = mysqli_fetch_array(mysqli_query($con, "SELECT type, size FROM datas WHERE imagesnotes='$imagesnotes'"), MYSQLI_ASSOC);
    header("Content-length:" . $sql['size']);
    header("Content-Disposition: attachment; filename=" . $imagesnotes);
    header("Content-Transfer-Encoding: Binary");
    header("$target_file");
    echo $sql['content'];
    }
    mysqli_close($con);
?>
</body>
</html>

【问题讨论】:

  • 也许这只是一个错误:download.php?id=应该是download.php?id==$id;?>跨度>
  • @m_pro_m 感谢它显示文件名的帮助,但它仍然将我带到上一页如何才能下载该选定文件?
  • 应该是

标签: php hyperlink download


【解决方案1】:

我在您的 download.php(第一个文件)中没有看到 $_GET['id'] 的管理,并且您在 download2.php(第二个文件)中创建了指向 download.php(第一个文件)的链接。所以它只是打印 download.php 页面内容。 您应该重定向到另一个管理 $_GET['id'] 的页面(download3.php ?)以重定向到真正的文件链接,或者首先在 download.php 中执行此操作,如果未提供 $_GET['id'] 则打印 download.php .

如果您还没有这样做,请在您的 MySQL 表中分配和 ID,如下所示:

id | filename
-----------------
1  | myfile.zip
2  | myfile2.rar

然后把它放在 download.php 的顶部或一个新的 download3.php 中(不要忘记在 download2.php 中上传链接):

<?php
if ($_GET['id'] != "") {
  $id = $_GET['id'];
  // Query your database to get the filename corresponding to $id and save it in a $filename variable
  header('Location: uploads/'.$filename);
  // Dont forget to change "uploads" to your real uploads folder
}
?>

还有download2.php中的链接id打印错误,使用:&lt;?php echo $id; ?&gt;


编辑:根据您更新的问题。请阅读我编写的代码中的 cmets。

文件名:“mysql.php”

目的:压缩 mysqli 函数,避免在更改数据库用户/密码时编辑每个文件。

注意事项:编辑 define() 变量以设置您的数据库用户/密码。

<?php
define("MYSQL_SERVER", "localhost");
define("MYSQL_USER", "root");
define("MYSQL_PASS", "YourPassword");

// Query function to use when expecting single result row or no result
// USAGE when needing query result:
// $result = mysqli_fetch_array(query("db_name", "SELECT column1, column2 FROM table_name WHERE column3='$something'"), MYSQLI_ASSOC);
// or
// USAGE when NOT needing query result:
// query("db_name", "INSERT INTO table_name (column1, column2) VALUES ('$column1_value','$column2_value') ");
function query($db, $arg) {
    $con = mysqli_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, $db)
        or die("Cannot connect: " . mysqli_error());
    $query = sprintf($arg);
    $result = mysqli_query($con, $query);
    mysqli_close($con);
}
// Creates a multidimensional array from query result, to use when expecting multiple result rows
// $type is the array type, accepted values are MYSQLI_ASSOC or MYSQLI_NUM or MYSQLI_BOTH
// usually MYSQLI_ASSOC is good
// USAGE:
// mysqli_fetch_alls("db_name", "SELECT column1, column2 FROM table_name WHERE column3='$something'", MYSQLI_ASSOC);
function mysqli_fetch_alls($db, $arg, $type) {
    $data = query($db, $arg);
    $result = array();
    $i = 0;
    while($row = mysqli_fetch_array($data, $type))
    {
        $result[$i] = $row;
        $i++;
    }
    return $result;
}

?>

文件名:“download.php”

目的:创建一个包含所有可下载文件列表的表单。

注意事项:检查mysqli_fetch_alls(),确保数据库表名正确。

<!DOCTYPE html>
<html>
<head>
<title>Download your friend's uploads</title>
</head>
<body>
<form action="download2.php" method="post">
<?php
    // Let's load mysql.php where are defined MySQL database parameters and query functions
    if (!defined('ABSPATH'))
        define('ABSPATH', dirname(__FILE__) . '/');
    require_once(ABSPATH . 'mysql.php');
    session_start();
    $username = $_SESSION["uname"];
    // Set database name
    $db = "webpage";
    // Query the database. Expecting multiple result rows: let's use mysqli_fetch_alls() function
    $sql = mysqli_fetch_alls($db, "SELECT imagesnotes FROM userdata WHERE sharedpeople='$username'", MYSQLI_ASSOC);
    echo "File or Image";
    echo'<select name="imagesnotes">';
    echo'<option value="" selected>Select a File</option>';
    // Print results
    for ($i = 0; $i < count($sql); $i++)
        echo'<option value="' . $sql[$i]['imagesnotes'] . '">'. $sql[$i]['imagesnotes'] .'</option>';
    echo'</select>';
?>
<input name="download" type="submit" class="box" id="download" value="download">
</form>
</body>
</html>

文件名:“download2.php”

用途:打印下载文件的链接。

注意事项:没什么好说的。

<!DOCTYPE html>
<html>
<head>
<title>Your download link is ready</title>
</head>
<body>
<?php
    // No need to query the database again, you get the filename from POST data
    echo '<br /><a href="download3.php?imagesnotes=' . $_POST['imagesnotes'] . '">Download your file</a><br />';
?>
</body>
</html>

文件名:“download3.php”

用途:打印文件内容。

注意事项:检查query(),确保数据库表名正确。

<!DOCTYPE html>
<html>
<head>
<title>Download your friend's uploads</title>
</head>
<body>
<?php
    // Let's load mysql.php where are defined MySQL database parameters and query functions
    if (!defined('ABSPATH'))
        define('ABSPATH', dirname(__FILE__) . '/');
    require_once(ABSPATH . 'mysql.php');
    session_start();
    $username = $_SESSION["uname"];
    // $_GET['imagesnotes'] is the GET parameter name printed in download2.php
    // as "download3.php?imagesnotes=filename"
    // If it was "download3.php?somethingelse=filename"
    // you should have looked for $_GET['somethingelse']
    if(isset($_GET['imagesnotes'])) 
    {
        $imagesnotes = $_GET['imagesnotes'];
        // Set database name
        $db = "webpage";
        // If $_GET['imagesnotes'] is set then get the file with that filename from database
        // Expecting a single result row: let's use mysqli_fetch_array(query(...), MYSQLI_ASSOC) function
        $sql = mysqli_fetch_array(query($db, "SELECT type, size, content FROM datas WHERE imagesnotes='$imagesnotes'"), MYSQLI_ASSOC);
        header("Content-length:" . $sql['size']);
        header("Content-type:" . $sql['type']);
        header("Content-Disposition: attachment; filename=" . $imagesnotes);
        echo $sql['content'];
    }
?>
</body>
</html>

回复您的更新 3

首先确保您的上传功能正常工作。这意味着您应该通过上传 php 脚本上传文件并通过 FTP 客户端下载文件以查看文件是否正确上传。如果是这样,那么请着手修复您的下载功能。

你的下载功能有几个错误。

$_FILES["fileToUpload"]["name"]

您为什么希望这会重新运行某些内容? - 见PHP $_FILES

header("$target_file");

真的没有任何意义 - 请参阅 PHP header() function

echo $sql['content'];

没有打印任何内容,因为您没有存储任何内容。

这是您的下载功能的外观。无需调用数据库,您将文件名作为 $_GET 参数传递。

<?php
    session_start();
    $username = $_SESSION["uname"];
    if(isset($_GET['imagesnotes'])) {
        $filename = $_GET['imagesnotes'];
        $dir = "uploads/";
        $file = $dir . $filename;
        if (file_exists($filename)) {
        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Transfer-Encoding: Binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
    }
    else
        echo "File not found!";
    exit;
    }
?>

【讨论】:

  • 尝试将$fp = fopen($tmpName, 'r');更改为$fp = fopen($tmpName, 'rb');
  • 不,我也一样。这可能是因为像 utf8_general_ci 这样的 blob 字符吗?
  • 也许吧。为什么不考虑将文件存储在文件夹中而不是数据库表中的 blob?这会让你的生活更轻松。
  • 如何在不使用数据库的情况下提供该文件,或者如何将文件上传到文件夹?
  • 阅读this 或只是谷歌“php 文件上传”,你会发现大量的例子
【解决方案2】:
<?php=$id;?> 

应该是

<?php echo $id; ?>

只要做:

header('Location: uploaddir/'.$_GET['id']);

例如如果文件是:document.docx

header('Location: uploaddir/document.docx');

会工作 如果 .htcaccess 配置正确,该文件将自动下载。 因此,如果这对您还不起作用:

How to configure .htcaccess

【讨论】:

  • 感谢您的帮助。但是上一页的方向错误依然存在。我将如何提供生成链接和下载文件?
猜你喜欢
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 2023-01-27
  • 2016-08-29
  • 1970-01-01
  • 2021-12-27
  • 2020-01-27
  • 1970-01-01
相关资源
最近更新 更多