Link to home
Start Free TrialLog in
Avatar of Moses Dwana
Moses Dwana

asked on

downloaded file from mysql database always gets corrupt or damage

Basically i want to store and be able to download word, excel pdf et.. file in mysql database. i have succeeded in storing the files but the download aspect is giving me hell. i wrote the script to down the files, but every time the downloaded files gets damage or corrupt. This is the error when i attempt to open the downloaded microsoft office document: we are sorry we can not open the file because we found problem with it content. this file is corrupt and can not be open.


please help, i have been on this for days.

this is my downlo.php file

if(isset($_GET["dow"])){
      ob_start();
      $path = $_GET['dow'];
      $mysqli = new mysqli("localhost","root","","extenderaid");
if($mysqli-> connect_error)
      die("database connection fail".$mysql->connect_error);

$qry = mysqli_query( $mysqli,"select doc from document where doc= '$path'");
header('Connection: Keep-Alive');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
readfile($path);

}




this is my upload file
include('section.php');
  
 $fload_error='';
  $discription_error='';
$discr='';
$submis_error='';
$submis='';
$ngo_error='';
$success='';
$target_file ='';
$quer ='';
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
	
}
    if (isset($_POST['submit']))  
    {  



if(empty($_POST["dis"])){
$discription_error = "require";
}else{ $discr = test_input($_POST["dis"]); 
if(!preg_match("/^[a-zA-Z]/",$discr)){
	$discription_error  = "require";	
}
}


if(empty($_POST["sub"])){
$submis_error = "require";
}else{ $submis = test_input($_POST["sub"]); 

}

if(empty($_POST["ngo"])){
$ngo_error = "require";
}




if($fload_error=='' and $discription_error=='' and $submis_error=='' and $ngo_error==''){
	
$mysqli = new mysqli("localhost","root","","extenderaid");
if($mysqli-> connect_error)
	die("database connection fail".$mysql->connect_error);

    
	
	    	  
//$result = mysqli_query($mysqli,"SELECT COUNT(*) FROM `document` where doc='$uplo'");
//$row = $result->fetch_row();
//$yes= $row[0];
	  
	  //if($yes <= 0){
		  
	 $myfile= $_FILES['myfile1']['name'];
	 $distri=$_POST['dis'];
	 $subdate=$_POST['sub'];
	  $ng=$_POST['ngo'];
	 $username=$_SESSION['login_user'];  
		 
	   $target_dir = "documentfile/";
       $target_file = $target_dir . basename($_FILES["myfile1"]["name"]);
       $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
	   if(!$myfile){
		   $fload_error="please select a file";
	   }
else if(file_exists($target_file)){
	$fload_error="file already exit";
}else if($imageFileType != "docx" && $imageFileType !="pdf" && $imageFileType != "xlsx"){
	$fload_error="only word, pdf and excel file allow";
}else if($_FILES['myfile1']['size'] > 500000){
	$fload_error="file size is too large";
}
else{	   
	 move_uploaded_file($_FILES["myfile1"]["tmp_name"], $target_file); 
	 $quer=mysqli_query($mysqli,"insert into document(ngo_id,docdiscription,doc,datesubmitted,insertedby) values ('$ng','$distri','  $target_file',' $subdate','$username')");
}
        if($quer){
			$success="inserted successifully";
			$discr=''; $submis=''; unset($_POST['submit']);	
		}
	    else{$fload= "error!";}
	  }
}

Open in new window


[/code]
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Your download code doesn't make a lot of sense. You run a query but do nothing with it. You then proceed to try and download the file from the path that has been passed in as a GET variable (potentially quite dangerous). There is no link between the file you're trying to download and the record in your database.
Avatar of Moses Dwana
Moses Dwana

ASKER

Sorry i am new to programing. i did some research on youtube and saw someone doing it this way.  
as i was following the tutorial, i notice that the query was not link to any of the download functions but did not know what to do. i did exactly as he  did.  its my first time using the download script, i am not well acquainted with the functions to download files.  can you please show me the best way of doing this?
OK. Normally, instead of passing in the filename as part of your query string, you would pass in an ID. You would then use this ID to query against the DB, pull out the relevant filename and then use that in the download part of your script.

Something along these lines:

$hostname = 'localhost';
$username = 'yourUsername';
$password = 'yourPassword';
$database = "yourDb";

$mysqli = new mysqli($hostname, $username, $password, $database);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT filename FROM files WHERE id=?")) {
    $stmt->bind_param("s", $_GET['fileno']); // bind the fileno from the query string
    $stmt->bind_result($filename); // store the result in the $filename variable

    $stmt->execute(); // execute the query
    $stmt->fetch(); // fetch the result
}

Open in new window


You would then call your script with an ID number passed in, for example:

download.php?fileno=12

This would read a filename from the database that match an ID number (maybe an auto ID primary key). Once it's run, then name of the file that was stored in the DB will be stored in a variable called $filename. You can then use that in your download code:

if (file_exists($filename)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($filename));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filename));
    ob_clean();
    flush();
    readfile($filename);
    exit;
}

Open in new window

sorry i have not reply for three days now, I went on weekend. however, thanks so mush for your help.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.