Help on upload and download and mysql

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
tkuan77
Forum Newbie
Posts: 5
Joined: Fri Jul 30, 2010 2:07 am

Help on upload and download and mysql

Post by tkuan77 »

Hi guys,

I am trying to create a coding which allows users to upload and download files into mysql server, but I came across some errors. The coding itself works fine on the surface, but when I uploaded the file into mysql and download them, the contents of the downloaded file was different from the original file that was upload. One good example would be when I upload txt file or doc file. I was stuck on this for quite a few days without any leads.

Here are the codes:

index.html

<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
<a href="list_files.php">See all files</a>
</p>


add_file.php

<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);

// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";

// Execute the query
$result = $dbLink->query($query);

// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}

// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}

// Echo a link back to the main page
echo '<p>Click <a href="index.html">here</a> to go back</p>';
?>


list_files.php

<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Query for a list of all existing files
$sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`';
$result = $dbLink->query($sql);

// Check if it was successfull
if($result) {
// Make sure there are some files in there
if($result->num_rows == 0) {
echo '<p>There are no files in the database</p>';
}
else {
// Print the top of a table
echo '<table width="100%">
<tr>
<td><b>Name</b></td>
<td><b>Mime</b></td>
<td><b>Size (bytes)</b></td>
<td><b>Created</b></td>
<td><b>&nbsp;</b></td>
</tr>';

// Print each file
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>{$row['name']}</td>
<td>{$row['mime']}</td>
<td>{$row['size']}</td>
<td>{$row['created']}</td>
<td><a href='get_file.php?id={$row['id']}'>Download</a></td>
</tr>";
}

// Close table
echo '</table>';
}

// Free the result
$result->free();
}
else
{
echo 'Error! SQL query failed:';
echo "<pre>{$dbLink->error}</pre>";
}

// Close the mysql connection
$dbLink->close();
?>


get_file.php

<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = intval($_GET['id']);

// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `file`
WHERE `id` = {$id}";
$result = $dbLink->query($query);

if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);

// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);

// Print data
echo $row['data'];
}
else {
echo 'Error! No image exists with that ID.';
}

// Free the mysqli resources
@mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
@mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>

I am not too sure where the error could be but I suspect that it could be somewhere at the add_file or get_file. Seriously hope someone could help me with this bug and thanks for the trouble.

Regards
Jasmine
bibumathew
Forum Newbie
Posts: 8
Joined: Tue Aug 03, 2010 5:36 pm

Re: Help on upload and download and mysql

Post by bibumathew »

Try this

It may work for u

get_file.php

<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = intval($_GET['id']);

// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `file`
WHERE `id` = {$id}";
$result = $dbLink->query($query);

if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);

$temp="temp/";
if(is_dir($temp))
{

foreach(glob($temp.'*.*') as $v){
unlink($v);
}

}else
{
mkdir("temp");
}

file_put_contents($temp.$row['name'],$row['data']);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $temp.$row['name']);


}
else {
echo 'Error! No image exists with that ID.';
}

// Free the mysqli resources
@mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
@mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
tkuan77
Forum Newbie
Posts: 5
Joined: Fri Jul 30, 2010 2:07 am

Re: Help on upload and download and mysql

Post by tkuan77 »

Hi bibumathew,

sorry for the late reply, my com was down for the past few days and I just managed to get it up and working. I tried out the coding you gave me but its still giving me the same error.

Any ideas?

Regards
Jasmine
Post Reply