dqo58772
dqo58772
2015-01-03 18:50

从数据库中选择文件时,不会生成下载链接

  • hyperlink
  • php
  • download
已采纳

I try to generate a link in order to download a file from my database. I make this with first select a file from drop down list then it directs you to another page and in that page it creates your link but when I want to do this if I click download file it returns me the previous page ant it doesn't create a link.
Here is my download.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>

From there user selects a image and clicks submit button.


Here is my 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);

?>

and here,it must create a link to download the file. What am I doing it wrong? Can you help me?Thanks.

Update:


so my final version of uploaded2.php is like this:

<?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);

?>

but it still brings me to the previous page. Why is it happening?
Update 2: So when I download the files, I download corrupted files. Here is my 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>


And Here is my uploaded.php to confirm the update operation:

<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>

What I'm doing it wrong? Thanks.
Update 3:Now I'm uploading my files to server not to database. but now I have a problem that I can't take that file for the download link. how can I do that?
here is my downloadyours.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>

here is my downloadyours2.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>

here is my downloadedyours.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>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • donglei1699 donglei1699 6年前

    I see no manage of $_GET['id'] in your download.php (first file) and your creating a link to download.php (first file) in download2.php (second file). So it just prints download.php page contents. You should redirect to another page (download3.php ?) that manages $_GET['id'] to redirect to the real file link, or do it in download.php as first and print download.php if no $_GET['id'] is provided.

    If you haven't yet done it, assign and ID in your MySQL table like this:

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

    Then place this on top of download.php or in a new download3.php (dont forget to upload link in 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
    }
    ?>
    

    Also link id print in download2.php is wrong, use: <?php echo $id; ?>


    EDIT: Basing on your updated question. Please read the comments inside the code i wrote.

    Filename: "mysql.php"

    Purpose: condense mysqli functions, avoid having to edit each file if you change your database user/password.

    Notes: edit define() variables to set your database user/password.

    <?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;
    }
    
    ?>
    

    Filename: "download.php"

    Purpose: create a form containing a list of all downloadable file.

    Notes: check mysqli_fetch_alls() and ensure that database table name is right.

    <!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>
    

    Filename: "download2.php"

    Purpose: print link to download file.

    Notes: nothing to say.

    <!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>
    

    Filename: "download3.php"

    Purpose: print file content.

    Notes: check query() and ensure that database table name is right.

    <!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>
    

    In reply to your Update 3

    First of all ensure your upload function is working properly. Which means you should upload a file via your uploading php script and download it via your FTP client to see if the file was uploaded correctly. If so, then move to fixing your download function.

    There are several errors in you're download function.

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

    Why are you expecting this to retrun something? - see PHP $_FILES

    header("$target_file");
    

    Doesnt really mean anything - see PHP header() function

    echo $sql['content'];
    

    Is printing nothing since you have nothing stored in it.

    Here's what your download function should look like. No need to call database, you're passing file name as $_GET parameter.

    <?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;
        }
    ?>
    
    点赞 评论 复制链接分享
  • dongqia0240 dongqia0240 6年前
    <?php=$id;?> 
    

    should be

    <?php echo $id; ?>
    

    Just do:

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

    For example if the file is: document.docx

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

    Will work The file will download automatically if the .htcaccess is configured correctly. So if this does not yet work for you:

    How to configure .htcaccess

    点赞 评论 复制链接分享