trouble with downloading a file once its uploaded

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

trouble with downloading a file once its uploaded

Post by cjkeane »

Hi.

I am developing script to allow visitors to upload and download files. they can upload the file successfully which gets saved into an 'upload' folder . The path with the filename isstored in a field in the database, as well as a description and the mimetype once the upload is a success. They can successfully delete it as well. My only issue is that when they click on the file to download it, nothing happens. Any help would be appreciated.
Thank you.

Code: Select all


<?php

$dbcnx = @mysql_connect('localhost', 'root', 'mypass');
if (!$dbcnx) {
  exit('<p>Unable to connect to the ' .
      'database server at this time.</p>');
}

if (!@mysql_select_db('uploads')) {
  exit('<p>Unable to locate the joke ' .
      'database at this time.</p>');
}

if (isset($_GET['action'])) {
  $action = $_GET['action'];
} else {
  $action = '';
}

if (($action == 'view' or $action == 'dnld') and isset($_GET['id'])) {
  $id = $_GET['id'];

  // User is retrieving a file
  $sql = "SELECT filename, mimetype, description FROM filestore WHERE id = '$id'";
  $result = @mysql_query($sql);
  if (!$result) {
    exit('Database error: ' . mysql_error());
  }
  
  $file = mysql_fetch_array($result);
  if (!$file) {
    exit('File with given ID not found in database!');
  }
    
  $uploadDir = '/upload/';
  $filename = $file['filename'];
  $mimetype = $file['mimetype'];
  //$filedata = $file['filedata'];
  $disposition = 'inline';
  $filePath = $uploadDir . $filename;
  
  if ($action == 'dnld') {
    $disposition = 'attachment';
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5') or
        strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7')) {
      $mimetype = 'application/x-download';
    }
  }
  
  header("content-disposition: $disposition; filename=$filename");
  header("content-type: $mimetype");
  //header('content-length: ' . strlen($filedata));
    
  //echo($filedata);
  exit();
  
} elseif ($action == 'del' and isset($_GET['id'])) {
  $id = $_GET['id'];
    
  // User is deleting a file
  $sql = "DELETE FROM filestore WHERE id = '$id'";
  $ok = @mysql_query($sql);
  if (!$ok) {
    exit('Database error: ' . mysql_error());
  }

  header('location: ' . $_SERVER['PHP_SELF']);
  exit();

} elseif (isset($_FILES['upload'])) {

  // Bail out if the file isn't really an upload.
  if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
    exit('There was no file uploaded!');
  }
  $uploadDir = '/upload/';
$tmpName = $_FILES['upload']['tmp_name'];
  $uploadname = $_FILES['upload']['name'];
  $uploadtype = $_FILES['upload']['type'];
  $uploaddesc = $_POST['desc'];
$filePath = $uploadDir . $uploadname;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}  

  // Create the SQL query.
  $sql = "INSERT INTO filestore SET
     filename = '$filePath',
      mimetype = '$filetype',
	  description = '$uploaddesc'";

  // Perform the insert.
  $ok = @mysql_query($sql);
  if (!$ok) {
    exit('Database error storing file: ' . mysql_error());
  }

  header('location: ' . $_SERVER['PHP_SELF']);
  exit();

}

// Default page view: lists stored files

$sql = 'SELECT id, filename, mimetype, description FROM filestore';
$filelist = @mysql_query($sql);
if (!$filelist) {
  exit('Database error: ' . mysql_error());
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP/MySQL File Repository</title>
<meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
</head>
<body>

<h1>PHP/MySQL File Repository</h1>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
    method="post" enctype="multipart/form-data">
  <p><label>Upload File:<br />
    <input type="file" name="upload" /></label></p>
  <p><label>File Description:<br />
    <input type="text" name="desc" maxlength="255" /></label></p>
  <p><input type="submit" value="Upload" /></p>
</form>

<p>The following files are stored in the database:</p>
<table>
<tr>
  <th>Filename</th>
  <th>Type</th>
  <th>Description</th>
</tr>
<?php

if (mysql_num_rows($filelist) > 0) {
  while ($f = mysql_fetch_array($filelist)) {
    ?>

<tr valign="top">
  <td>
    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=view&id=<?php echo $f['id']; ?>">
      <?php echo $f['filename']; ?></a>
  </td>
  <td><?php echo $f['mimetype']; ?></td>
  <td><?php echo $f['description']; ?></td>
  <td>
    [<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=dnld&id=<?php echo $f['id']; ?>"
      >Download</a> |
    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=del&id=<?php echo $f['id']; ?>"
      onclick="return confirm('Delete this file?');"
      >Delete</a>]
  </td>
</tr>

    <?php
  }
} else {
  ?>
  <tr><td colspan="3">No Files!</td></tr>
  <?php
}
?>
</table>
</body>
</html>

User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: trouble with downloading a file once its uploaded

Post by Benjamin »

Enable error reporting and narrow down the point of failure.
whizzopia
Forum Newbie
Posts: 8
Joined: Sun Sep 02, 2007 6:17 pm

Re: trouble with downloading a file once its uploaded

Post by whizzopia »

Don't forget to put readfile()

Code: Select all

header("content-disposition: $disposition; filename=$filename");
header("content-type: $mimetype");
readfile($filename);
http://php.net/manual/en/function.header.php
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: trouble with downloading a file once its uploaded

Post by cjkeane »

I now am able to download files so I am closer to get the script working.

my only problem now is that when `the `delete`link is clicked, it does delete the entry in the database, but fails to delete the file from the upload folder. My updated code is below.

Code: Select all


<?php
$dbcnx = @mysql_connect('localhost', 'root', 'mypass');
if (!$dbcnx) {
  exit('<p>Unable to connect to the ' .
      'database server at this time.</p>');
}
if (!@mysql_select_db('uploads')) {
//if (!@mysql_select_db('ijdb')) {
  exit('<p>Unable to locate the joke ' .
      'database at this time.</p>');
}

if (isset($_GET['action'])) {
  $action = $_GET['action'];
} else {
  $action = '';
}

if (($action == 'view' or $action == 'dnld') and isset($_GET['id'])) {
  $id = $_GET['id'];

  // User is retrieving a file
  $sql = "SELECT filename, mimetype, description FROM filestore WHERE id = '$id'";
  $result = @mysql_query($sql);
  if (!$result) {
    exit('Database error: ' . mysql_error());
  }
  
  $file = mysql_fetch_array($result);
  if (!$file) {
    exit('File with given ID not found in database!');
  }
    
  $uploadDir = "upload/";
  $filename = $file['filename'];
  $mimetype = $file['mimetype'];
  //$filedata = $file['filedata'];
  $disposition = 'inline';
  $filePath = $uploadDir . $filename;
  
  if ($action == 'dnld') {
    $disposition = 'attachment';
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5') or
        strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7')) {
      $mimetype = 'application/x-download';
    }
  }
  
 header("content-disposition: $disposition; filename=$filename");
header("content-type: $mimetype");
readfile($filename);
  //header('content-length: ' . strlen($filedata));
    
  //echo($filedata);
  exit();
  
} elseif ($action == 'del' and isset($_GET['id'])) {
  $id = $_GET['id'];
    
  // User is deleting a file
  $sql = "DELETE FROM filestore WHERE id = '$id'";
  $ok = @mysql_query($sql);
  unlink($filename);
  if (!$ok) {
	 
    exit('Database error: ' . mysql_error());
	
	
  }

  header('location: ' . $_SERVER['PHP_SELF']);
  exit();

} elseif (isset($_FILES['upload'])) {

  // Bail out if the file isn�t really an upload.
  if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
    exit('There was no file uploaded!');
  }
  $uploadDir = "upload/";
$tmpName = $_FILES['upload']['tmp_name'];
  $uploadname = $_FILES['upload']['name'];
  $uploadtype = $_FILES['upload']['type'];
  $uploaddesc = $_POST['desc'];
$filePath = $uploadDir . $uploadname;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}  

  // Create the SQL query.
  $sql = "INSERT INTO filestore SET
     filename = '$filePath',
      mimetype = '$uploadtype',
	  description = '$uploaddesc'";

  // Perform the insert.
  $ok = @mysql_query($sql);
  if (!$ok) {
    exit('Database error storing file: ' . mysql_error());
  }

  header('location: ' . $_SERVER['PHP_SELF']);
  exit();

}

// Default page view: lists stored files

$sql = 'SELECT id, filename, mimetype, description FROM filestore';
$filelist = @mysql_query($sql);
if (!$filelist) {
  exit('Database error: ' . mysql_error());
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP/MySQL File Repository</title>
<meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
</head>
<body>

<h1>PHP/MySQL File Repository</h1>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
    method="post" enctype="multipart/form-data">
  <p><label>Upload File:<br />
    <input type="file" name="upload" /></label></p>
  <p><label>File Description:<br />
    <input type="text" name="desc" maxlength="255" /></label></p>
  <p><input type="submit" value="Upload" /></p>
</form>

<p>The following files are stored in the database:</p>
<table>
<tr>
  <th>Filename (with path)</th>
  <th>Type</th>
  <th>Description</th>
</tr>
<?php

if (mysql_num_rows($filelist) > 0) {
  while ($f = mysql_fetch_array($filelist)) {
    ?>

<tr valign="top">
  <td>
    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=view&id=<?php echo $f['id']; ?>">
      <?php echo $f['filename']; ?></a>
  </td>
  <td><?php echo $f['mimetype']; ?></td>
  <td><?php echo $f['description']; ?></td>
  <td>
    [<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=dnld&id=<?php echo $f['id']; ?>"
      >Download</a> |
    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=del&id=<?php echo $f['id']; ?>"
      onclick="return confirm('Delete this file?');"
      >Delete</a>]
  </td>
</tr>

    <?php
  }
} else {
  ?>
  <tr><td colspan="3">No Files!</td></tr>
  <?php
}
?>
</table>
</body>
</html>

User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: trouble with downloading a file once its uploaded

Post by Jade »

Deleting the database record for the file isn't the same thing as deleting the file. Take a look at this http://php.net/manual/en/function.unlink.php
Post Reply