I can't seem to download my files online which I'm uploading into a MySQL database I only get plain text, vague signs mostly. In localhost though downloading is no problem. I checked my database online and locally both are uploaded good in the upload table. I'll show you Upload.php(It's not called that in real, and this is also not the entire script, It's a big script) first:
if (isset($_POST['verstuur'])) {
$id = NULL;
if($_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 upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Fout, query mislukt');
$query = "SELECT LAST_INSERT_ID() ID";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$id = $row['ID'];
}
}
Okay so I have another script where I create the download link:
$query = "SELECT U_ID, name FROM upload WHERE U_ID = '$opvraag[U_ID]'";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "<td>Geen Bijlage</td>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
echo '<td>'.$name.'</td>';
}
}
And Last I have download.php
if(isset($_GET['id']))
{
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE U_ID = '$id'";
$result = mysql_query($query) or die('Fout, query mislukt');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo stripslashes($content);
exit;
}
The Database Table:
Name: Type:
U_ID int(8) AUTO_INCREMENT
name varchar(255)
size int(8)
type text
content blob
Can you try replacing your 3 calls to headers() in your download.php with this:
header("Accept-Ranges: bytes");
header("Keep-Alive: timeout=15, max=100");
header("Content-Disposition: attachment; filename=$name");
header("Content-type: $type");
header("Content-Transfer-Encoding: binary");
header( "Content-Description: File Transfer");
Related
in my project I need to upload pdf file and download it afterwards.
everything works fine , but after i download the pdf file its been currupted and i can't view it.
if i try to open it with Adobe Acrobat Reader i get this error that says the file been currupted and didn't encoded correctly.
can someone help me to resolve this? thanks!
php script for download and upload:
<?php
// connect to the database
require_once 'connectionoop.php';
require_once 'core/init.php';
$query1 = sprintf("SELECT files.id, files.name,files.size ,files.downloads , association.Aname ,projects.Pname,files.project
FROM files
INNER JOIN projects ON files.project = projects.id INNER JOIN association ON projects.Aid = association.id
");
$result1 = $mysqli->query($query1);
$files=array();
foreach ($result1 as $row) {
$files[] = $row;
}
// Uploads files
if (isset($_POST['save'])) { // if save button on the form is clicked
// name of the uploaded file
$filename = $_FILES['myfile']['name'];
$proj = $_POST['Aid'];
// destination of the file on the server
$destination = 'uploads/' . $filename;
// get the file extension
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// the physical file on a temporary uploads directory on the server
$file = $_FILES['myfile']['tmp_name'];
$size = $_FILES['myfile']['size'];
if (!in_array($extension, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['myfile']['size'] > 1000000) { // file shouldn't be larger than 1Megabyte
echo "File too large!";
} else {
// move the uploaded (temporary) file to the specified destination
if (copy($file, $destination)) {
$query = sprintf("INSERT INTO files (name, size, downloads , project) VALUES ('$filename', $size, 0,$proj)");
//execute query
$result = $mysqli->query($query);
$sql = "INSERT INTO files (name, size, downloads) VALUES ('$filename', $size, 0)";
$pr=new Project($proj);
$pr->update(array(
'hasfile' =>1
));
Redirect::to('downloads.php');
} else {
echo "Failed to upload file.<br>".$destination;
}
}
}
if (isset($_GET['file_id'])) {
$id = $_GET['file_id'];
$query2 = sprintf("SELECT * FROM files WHERE id=$id");
// fetch file to download from database
$result2 = $mysqli->query($query2);
$data = array();
foreach ($result2 as $row) {
$data[] = $row;
}
$filepath = 'uploads/' .$data[0]['name'];
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('uploads/' . $data['name']));
readfile('uploads/' . $data['name']);
// Now update downloads count
$newCount = $data['downloads'] + 1;
$query3 = sprintf("UPDATE files SET downloads=$newCount WHERE id=$id");
// fetch file to download from database
$result3 = $mysqli->query($query3);
exit;
}
}
It should be header("Content-type:application/pdf");
In my website, I want to allow the user to upload files (they will be stored in a database) and then allow them to download the uploaded files after that. The uploading process is done without errors and they are saved in binary.
The downloading process also works but the downloaded files are corrupted !
Any idea why?
The uploading code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$studentId = $_POST['studentId'];
fclose($fp);
$query = "INSERT INTO file (studentId, fileName, fileType, fileContent ) ".
"VALUES ('$studentId', '$fileName', '$fileType', '$content')";
mysql_select_db($database_databasestudents, $databasestudents);
mysql_query($query) or die('Error, query failed');
header("Location: students.php");
die();
?>
The download code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
mysql_select_db($database_databasestudents, $databasestudents);
$query = 'SELECT fileName, fileContent, fileType, LENGTH(fileContent) as fileSize from file WHERE id="'. $_GET ['id'].'";';
$Recordset1 = mysql_query($query, $databasestudents) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_BOTH);
$size = $row['fileSize'];
$type = $row['fileType'];
$name =$row['fileName'];
$fileContent = $row['fileContent'];
echo $size . "". $type . " ". $name;
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $fileContent;
mysql_close();
?>
Use PDOs and prepared statements. This may fix the issue, and it will fix the SQL injection vulnerability in the download code (which currently allows people to hack your database).
PDO has "large objects" (LOBs) support meant for exactly what you are doing. It will be much more efficient than what you are currently doing. The documentation provides excellent example code which does more or less exactly what you want.
I've figured it out .. jus removing this line from the download code:
echo $size . "". $type . " ". $name;
I have created a upload form and a php file which extract the name, size, type of the file and stores it in a database upload script, in table files. The file is also given a uniqid which is also stored in the same table.
Now I am trying to build up a download.php file where I want that when a specific link with the uniqid in is opened the script look in databse for the file searching for the uniqid and show the information against it.?
Here is my upload.php
<?php
include('config.php');
function bytesToSize1024($bytes, $precision = 300) {
$unit = array('B','KB','MB');
return #round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}
$FileName = $_FILES['filename']['name'];
$FileType = $_FILES['filename']['type'];
$FileSize = bytesToSize1024($_FILES['filename']['size'], 1);
$Fileid = uniqid(rand());
$tmp_name = $_FILES["filename"]["tmp_name"];
if ($_FILES["filename"]["error"] > 0)
{
echo "Apologies, an error has occurred.";
echo "Error Code: " . $_FILES["fileToUpload"]["error"];
}
else
{
move_uploaded_file($_FILES["filename"]["tmp_name"],
"C:\wamp\www\upload\upload" . $_FILES["filename"]["name"]);
}
$query2 = "INSERT INTO files (id, name, size, type) VALUES ('$Fileid', '$FileName', '$FileSize', '$FileType')";
$result2 = mysql_query($query2);
echo <<<EOF
<p>Your file: {$FileName} has been successfully received.</p>
<p>Type: {$FileType}</p>
<p>Size: {$FileSize}</p>
<p>Temp Foler: {$tmp_name}</p>
<p>Download Link: localhost/upload/download.php?=$Fileid
EOF;
?>
Please first tell me which kind of link I should create like. localhost/download.php?=uniqid
will the above example work and how to make it work. I am confused?
Here I have tried to create a download.php file but it is not good
<?php
include('config.php');
$query = "SELECT * FROM files";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
?>
<?php
echo <<<EOF
File Name: <?php echo $row['name']; ?>
$row
EOF;
?>
This is the code you need. Consider storing byte count in the database for file size.
Of course it might need some changes to be exactly what you want.
<?php
include('config.php');
//get id from GET method and make sure that it's safe to be used in the query
$id=mysql_real_escape_string($_GET['id']);
$query = "SELECT * FROM `files` WHERE `id`='$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (count($row)!=1) //check if our unique record has been found
die('Sorry but we could not find this file!');
$row=$row[0];
//send download headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$row['name']);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: no-cache');
header('Content-Length: ' .$row['size']);
readfile(upload" . $row['name']); //I recommend you to change the path and file name of your uploaded files!
?>
Link example: http://yourdomain.com/download.php?id=123
I'm able to upload a file to mysql but when i download it, the content changes.. example i have test.txt with
"hello"
on it.. when i download it, the test.txt becomes
< pre class='xdebug-var-dump' dir='ltr'>string 'sfasfsafasfsaf' (length=14)
sfasfsafasfsaf
not sure, what's wrong..
this is my code for downloading the file:
<?php include("class_lib.php");
$db = new database();
$db->connect();
if(isset($_GET["file_id"])){
$file_id = $_GET["file_id"];
$query = "SELECT filename, filetype, filesize, bin_data " .
"FROM file_tbl WHERE id = '$file_id'";
$result = mysql_query($query) or die('Error, query failed' . mysql_error());
list($filename, $filetype, $filesize, $bin_data) = mysql_fetch_array($result);
var_dump($bin_data);
header("Content-length: $filesize");
header("Content-type: $filetype");
header("Content-Disposition: attachment; filename=$filename");
echo $bin_data;
}
?>
for images also, it downloads but there's no image anymore.. it only shows "no preview available".. is this with my download script above?
or maybe this upload script i have:
$fileid = (string) ($lastemp_id + 1);
$fileName = basename($_FILES['binFile']['name']);
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$fileName .= "_fileid_" . $fileid;
$fileName = $fileName.".".$extension;
$tmpName = $_FILES['binFile']['tmp_name'];
$fileSize = $_FILES['binFile']['size'];
$fileType = $_FILES['binFile']['type'];
$fileDesc = $_POST["txtDescription"];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()){ $fileName = addslashes($fileName); }
if (isset($fileName)) {
$sql = "INSERT INTO file_tbl ";
$sql .= "(file_desc, bin_data, filename, filesize, filetype) ";
$sql .= "VALUES ('$fileDesc', '$content', ";
$sql .= "'$fileName', '$fileSize', '$fileType')";
mysql_query($sql, $db->connection) or die('Error: query failed' . mysql_error());
$message = "File uploaded.<br>"; var_dump($content);
}
else $message = "No file uploaded. (opt)";
what is wrong here exactly??
You're recklessly jamming binary data into your database without even a whiff of proper SQL escaping. What did you expect to happen? This short sample of code is so full of severe SQL injection bugs I hope for your sake it isn't deployed on the public internet.
For your own safety you should immediately stop using the creaky, old, deprecated mysql_query interface and spend the small amount of time necessary to switch your queries to PDO.
You would not have problems like this if you were using placeholders.
What you're seeing is probably the result of your spurious var_dump statement before you output your proper content.
Please try this, if upload file is flawless.
You can encode your binary data to 64 format when insert into database and also decode before download it.
<?php
ob_start();
include("class_lib.php");
$db = new database();
$db->connect();
if(isset($_GET["file_id"])){
$file_id = $_GET["file_id"];
$query = "SELECT filename, filetype, filesize, bin_data " .
"FROM file_tbl WHERE id = '$file_id'";
$result = mysql_query($query) or die('Error, query failed' . mysql_error());
list($filename, $filetype, $filesize, $bin_data) = mysql_fetch_array($result);
var_dump($bin_data);
ob_end_clean();
header("Content-length: $filesize");
header("Content-type: $filetype");
header("Content-Disposition: attachment; filename=$filename");
echo $bin_data;
exit;
}
?>
I have a classifieds website where users must fill in a form in order to put a ad. The form consists of name, password, category, specifications etc etc.
Now, I need to add a image upload function into this form, which must have the following:
1- Upload up to 5 images.
2- A 'remove image link' beneath each image if the user wants another image instead.
How would you do this?
Thanks
Best would be if there was a plugin or something to Jquery which is easy to modify...
jQuery Multiple File Upload
You can limit the number of uploads using the max option or passing a number as the only parameter. More info on the Examples tab.
If you want to upload it as a file to an SQL database, have something like this in the form (in php echo format):
echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2000000\">
<input name=\"userfile\" type=\"file\" id=\"userfile\">";
Then in your form's receiving php page put something like this:
if ($_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 files (name, size, type, content ) VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
$thisq = mysql_query("SELECT * FROM `files` WHERE 1 ORDER BY `id` DESC LIMIT 1");
$fileidnumber= mysql_fetch_array($thisq);
}
That will store the file to a database and then return the key for you to save or use however you'd like. You can then create a page to download the files like this:
<?php
import_request_variables(gp);
if(isset($_GET['id'])) {
// if id is set then get the file with the id from database
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM `files` 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");
echo $content;
exit;
}
?>