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!
<?php
@mysql_connect('localhost', 'root', 'dbstuff3r');
@mysql_select_db('extranet');
$self = $_SERVER['PHP_SELF'];
// always good to check that the ID is not empty and that it is definitely
// a number
if (!empty($_GET['id']) && is_numeric($_GET['id'])) {
// I like to ensure that the number is an integer.
$id = (int)$_GET['id'];
// if `id` is a number then you don't need to put quotes around it.
$query = "SELECT file_data, id, name, file_type, file_size, downloads FROM files WHERE id=$id";
@$result = mysql_query($query);
// it's a good idea to check that a result was returned before attempting
// to use the data.
if (mysql_num_rows($result) == 1) {
// if you only want the associative array then you can use
// mysql_fetch_assoc() instead of mysql_fetch_array().
$row = mysql_fetch_assoc($result);
$type = $row['file_type'];
$name = $row['name'];
$size = $row['file_size'];
$id = $row['id'];
$data = urldecode($row['file_data']);
$downloads = $row['downloads'];
header('Content-type: '.$type);
header('Content-length: '.$size);
header('Content-Disposition: attachment; filename='.$name);
header('Content-Description: PHP Generated Data');
echo $data;
exit;
} else {
echo 'That download is not available. Please try again.';
}
} else {
$query = "SELECT id, name, file_type, file_size, downloads FROM files";
$result = mysql_query($query) or die('Can''t execute!'.mysql_error());
// you need to be careful with either escaping double quotes within
// a double quoted string,
// e.g. echo "<table summary="files" border="1">";
// or use single quotes around your HTML, or escape the PHP to go into
// HTML, like below:
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Download</title>
</head>
<body>
<h1 style="text-align: center;">Choose a file to download</h1>
<div style="text-align: center;">
<table summary="files" border="1">
<tr style="background-color: #ffffcc;">
<th>File name</th>
<th>Size</th>
<th>File Type</th>
<th>Download</th>
<th>Downloads</th>
</tr>
<?php
while($row=mysql_fetch_assoc($result)) {
$type = $row['file_type'];
$name = $row['name'];
$size = $row['file_size'];
$id = $row['id'];
$downloads = $row['downloads'];
?>
<tr>
<td><?php echo $name; ?></td>
<td><?php echo $size; ?></td>
<td><?php echo $type; ?></td>
<td><a href="<?php echo $self; ?>?id=<?php echo $id; ?>">Download</a></td>
<td><?php echo $downloads; ?></td>
</tr>
<?php
} // end while
?>
</table>
</div>
</body>
</html>
<?php
} // end else
?>