Jump to content

Download file from Mysql


RidgeandGable

Recommended Posts

Hiya guys

After getting everything else working how I expected, I'm sort of struggling on the last step. Downloading

I have an upload.php file that allows me to upload a file to Mysql, the fields available are:

upid - Primary
id - Need to link this to the logged on user id

name
type
size

content

 

The upload works perfectly

Can anyone help with implmenting it to the profile.php (1st page after login)

On profile page I have:

Welcome "username" from Session
Dynamic Table display his user id, username and password at the moment, this will be changed as not needed tho. I am using the sessions MM_Username to pass from the login

The table for Login looks like:

id - primary

username

password

I assume that if I can copy the ID from login and put it in ID in Upload and add colums to dynamic table to show the upload file, will this make that file only available to logged in user?

Cheers

Link to comment
Share on other sites

Just an update, I managed to get everything linking and now the logged in user can see his own files :D but, there is an option to download the files and rather than display just his files, he gets the option to dwnload all files

Heres the script for the download part

 

<?php
        $con = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
        $db = mysql_select_db('company', $con);
        $query = "SELECT username, name FROM upload";
        $result = mysql_query($query) or die('Error, query failed');
        if (mysql_num_rows($result) == 0) {
            echo "Database is empty <br>";
        } else {
            while (list($id, $name) = mysql_fetch_array($result)) {
                ?>
                <a href="download.php?username=<?php echo urlencode($username); ?>"
                   ><?php echo urlencode($name); ?></a> <br>
                <?php
            }
        }
        mysql_close();
        ?>
    </body>
</html>
           <?php
           if (isset($_GET['username'])) {
               $con = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
               $db = mysql_select_db('company', $con);
               $username = $_GET['username'];
               $query = "SELECT name, type, size, content " .
                       "FROM upload WHERE username = '$username'";
               $result = mysql_query($query) or die('Error, query failed');
               list($username, $name, $type, $size, $content) = mysql_fetch_array($result);
               header("Content-link: $username");
			   header("Content-length: $size");
               header("Content-type: $type");
               header("Content-Disposition: attachment; filename=$name");
               ob_clean();
               flush();
               echo $content;
               mysql_close();
               exit;
           }
           ?>;</td>

Above is what I have amended to try and make it, original code below

 

<html>
    <head>
        <title>Download File From MySQL Database</title>
        <meta http-equiv="Content-Type" content="text/html; 
              charset=iso-8859-1">
    </head>
    <body>
        <?php
        $con = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
        $db = mysql_select_db('test', $con);
        $query = "SELECT id, name FROM upload";
        $result = mysql_query($query) or die('Error, query failed');
        if (mysql_num_rows($result) == 0) {
            echo "Database is empty <br>";
        } else {
            while (list($id, $name) = mysql_fetch_array($result)) {
                ?>
                <a href="download.php?id=<?php echo urlencode($id); ?>"
                   ><?php echo urlencode($name); ?></a> <br>
                <?php
            }
        }
        mysql_close();
        ?>
    </body>
</html>
           <?php
           if (isset($_GET['id'])) {
               $con = mysql_connect('localhost', 'username', password') or die(mysql_error());
               $db = mysql_select_db('test', $con);
               $id = $_GET['id'];
               $query = "SELECT name, type, size, content " .
                       "FROM upload WHERE id = '$id'";
               $result = mysql_query($query) or die('Error, query failed');
               list($name, $type, $size, $content) = mysql_fetch_array($result);
               header("Content-length: $size");
               header("Content-type: $type");
               header("Content-Disposition: attachment; filename=$name");
               ob_clean();
               flush();
               echo $content;
               mysql_close();
               exit;
           }
           ?>

I have a session available called MM_Username which pulls the logged in user to filter everything else.

Tbl Login:
ID - Primary
Username
Password

Tbl Upload
upid - Primary
ID - For Login

username
name

type

size

content

 

A viewing can be seen at http://scotair.noip.me/new.php alex is password and username

 

If you look, Alex has actually got 3 files available, whilst the download at the side has 4 files (all files from mysql) file axismapping.dat belongs to another user with ID 3 and Username Fugo
 

Link to comment
Share on other sites

In profile.php you'd just fetch the records that match the users username from the uploads table. You'd then output the details for each file returned by the query, eg filename and filesize. You'd make the filename a link to your download script. The link will contain a file id query string parameter set to the upid of the file.

 

Basic example code for profile.php for showing the users uploaded files

echo '<h2>Uploaded Files</h2>';

// get the files belonging to the logged in user
$result = mysql_query('SELECT upid, filename, size FROM upload WHERE username=\''.mysql_real_escape_string($_SESSION['MM_Username'].'\'');

// check query did execute without errors
if($result)
{
    // output each file
    while($row = mysql_fetch_assoc($result))
    {
       // set a link to download.php passing the files upid as a query string parameter
       echo '<a href="download.php?upid='.$row['upid'].'">'.$row['filename'] - $row['size'].'</a><br />';
    }
// query did not execute, log or show error message
} else {
    trigger_error('Cannot get users files from database: ' . mysql_error());
}

.

 

Now in download.php you'd run a query fetch the row where the upid field matches $_GET['upid'] in the uploads table. If the query returns a row you'd present the file for download. Basic download.php example code

<?php
session_start();

// very basic check to see if user is logged in
if(!isset($_SESSION['MM_Username']))
{
    // kill the script display warning.
    die('Unauthorised accessed. You must be logged in to access this file');
}

// Has a file id been passed? 
if(isset($_GET['upid']) && ctype_digit($_GET['upid']))
{
    // fetch the file where the upid matches
    $result = mysql_query('SELECT filename, type, size, content FROM upload WHERE upid='.intval($_GET['upid']));

    // query executed ok
    if($result)
    {
         // get the files details
         list($filename, $type, $size, $content) = mysql_fetch_row($result);

         // present file for download
         header("Content-length: $size");
         header("Content-type: $type");
         header("Content-Disposition: attachment; filename=$filename");
         echo $content;
         exit;
    }
}
Edited by Ch0cu3r
Link to comment
Share on other sites

Yip that got rid of that error now I get 1 more error, probably something I missed

 

Notice: Cannot get users files from database: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''alex\'' at line 1 in C:\xampp\htdocs\ridge\success.php on line 81

 

I created a new page rather than copying over other codes etc to reduce any errors, this is the new page for profile, new name Success.php

<?php require_once('Connections/new.php'); ?>
<?php if (!isset($_SESSION)) {
  session_start();
}
 ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$colname_Recordset1 = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_Recordset1 = $_SESSION['MM_Username'];
}
mysql_select_db($database_new, $new);
$query_Recordset1 = sprintf("SELECT * FROM login WHERE username = %s", GetSQLValueString($colname_Recordset1, "text"));
$Recordset1 = mysql_query($query_Recordset1, $new) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
 <p>Hello <?php echo $_SESSION['MM_Username']?> !</p>
 <p> </p>
 <p> </p>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>
<?PHP
echo '<h2>Uploaded Files</h2>';

// get the files belonging to the logged in user
$result = mysql_query('SELECT upid, filename, size FROM upload WHERE username=\''.mysql_real_escape_string($_SESSION['MM_Username'].'\''));

// check query did execute without errors
if($result)
{
    // output each file
    while($row = mysql_fetch_assoc($result))
    {
       // set a link to download.php passing the files upid as a query string parameter
       echo '<a href="download.php?upid='.$row['upid'].'">'.$row['filename'] - $row['size'].'</a><br />';
    }
// query did not execute, log or show error message
} else {
    trigger_error('Cannot get users files from database: ' . mysql_error());
}
?>

Edited by RidgeandGable
Link to comment
Share on other sites

Ha classic.. I can be such a tool sometimes.

 

Code should now be error free

echo '<h2>Uploaded Files</h2>';

// get the files belonging to the logged in user
$result = mysql_query('SELECT upid, filename, size FROM upload WHERE username=\''.mysql_real_escape_string($_SESSION['MM_Username']).'\'');

// check query did execute without errors
if($result)
{
    // output each file
    while($row = mysql_fetch_assoc($result))
    {
       // set a link to download.php passing the files upid as a query string parameter
       echo '<a href="?upid='.$row['upid'].'">'.$row['filename'].' - '.$row['size'].'</a><br />';
    }
// query did not execute, log or show error message
} else {
    trigger_error('Cannot get users files from database: ' . mysql_error());
}
Link to comment
Share on other sites

Strange, I got it working all by myself :D

Instead of having to click on the filename in Success.php and then that directs to Download.php, if I just paste the contents of download.php into the bottom of success.php it downloads the file however, whatever file I download appears to be corrupt.

Letter1.PDF when try to open the file it says - Failed to Load PDF Document. Adobe PDF Reader
Download Formget.jpg - This is not a valid bitmap / jpeg file

Link to comment
Share on other sites

I just uploaded a txt file called text.txt and the file only had my name in it, no other text, after I downloaded the file, I opened it and found this

 

Hello alex !</p>
<h2>Uploaded Files</h2><a href="?upid=11">A4 Invoice CREDIT.pdf - 25059</a><br /><a href="?upid=12">test.txt - 7</a><br /><br />
<b>Notice</b>:  A session had already been started - ignoring session_start() in <b>C:\xampp\htdocs\ridge\success.php</b> on line <b>31</b><br />
Harry
 
Any ideas ?
Link to comment
Share on other sites

I've got the following:

 

 

Hello alex !</p>
<h2>Uploaded Files</h2><a href="?upid=7">images.jpg - 16156</a><br /><a href="?upid=11">A4 Invoice CREDIT.pdf - 25059</a><br /><a href="?upid=12">test.txt - 7</a><br /><a href="?upid=13">test.txt - 7</a><br /><a href="?upid=14">test.txt - 7</a><br />Harry

 

Is this what you expected to be?

Link to comment
Share on other sites

if I just paste the contents of download.php into the bottom of success.php

 

the http response for the download request must only consist of the header statements and the content of the file you want to download.

 

what you are seeing in the downloaded file is the content of the file and the html that's being output on your success.php page, making the file invalid.

Link to comment
Share on other sites

Ah ok so the downloading setion must be a page. When its on its own i cant get it working, no files to see and no error messages

A couple notes for download.php I have omitted the code for connecting to mysql so you must add the code you use for connecting to mysql before the first if statement. I have also omitted the code for outputting an error if the query fails.

 

This is why I think you are getting a blank white page. Adding the missing pieces of code should get download.php to function.

Link to comment
Share on other sites

lol omg I did think about a connection to the database but thought nah, won't be as simple as adding <?php require_once('/Connections/new.php'); ?> so I left it out, changed the select statement from select name etc to select * incase I was missing a spelling error or something.

Added <?php require_once('/Connections/new.php'); ?> and working with valid files

 

Thank you so so much for all your help guys expc, Ch0cu3r

 

I'll be in touch when I start the picture gallery lol :D

However, no the code is there and working, I should be able to use all this as a reference to fall back on.

I have downloaded & printed a book for Mysqli and PDO, so I'll be looking into changing to PDO I think for any future upgrades but will see how everything runs for a month or two first

Thanks again

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.