0

When I upload a pdf file to database and then I downlaod it, it can't be opened, beacause it's damaged. Am I doign something wrong in my script? In database i have two rows, "field_name" which is BLOB and id which is primary key.

<?php

function pripoj()
{
    $connect=mysqli_connect ('---','----','******','testovaciukol');
    if (mysqli_connect_errno())
    {
        die ("Failed to connect to MySQL: " . mysqli_connect_error());
    } 
    return $connect;
}

function sql($pripojeni,$prikaz)
{
    $vysledek=mysqli_query($pripojeni,$prikaz); 
    echo mysqli_error();
    return $vysledek;
}


function zavri($pripojeni)
{
    mysqli_close($con);
}

?>

<form method="post" enctype="multipart/form-data">

File: <input type="file" name="pdf" id="pdf" accept="application/pdf" 
title="Choose File" ><br>

<input type="submit" name="upload" id="upload" value="Upload" ><br>

<input type="submit" name="read" id="read" value="Read" >

</form>


<?php

$link=pripoj();

if(isset($_POST['upload'])) {

    $file_path=$_FILES['pdf']['tmp_name']; 
    $file_type=$_FILES['pdf']['type'];
    $file_size=$_FILES['pdf']['size'];
    $file_name=$_FILES['pdf']['name'];

    if ($file_name != "" && $file_type == 'application/pdf') {
        $data=mysqli_real_escape_string($link, file_get_contents($file_path));
        $query="INSERT INTO `testovaciukol`.`pdf` SET field_name = '".$data."'"; 

        $result = sql($link, $query); //query execution

        if($result)
            echo 'Success! Your file was successfully added!';
        else
            echo 'Error!';

    } else {

        echo 'Not a pdf file';
    }
}


if(isset($_POST['read'])) {

    $sql = "SELECT field_name FROM pdf WHERE id = '1'";
    $result2 = sql($link, $sql);    
    $row = mysqli_fetch_object($result2); resultset
    $pdf_content = $row->field_name; 
    $fileName = time().".pdf";
    header("Content-type: application/pdf");
    header("Content-disposition: attachment; filename=".$fileName);
    print $pdf_content;
}
?>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Erik
  • 303
  • 1
  • 3
  • 12
  • See this: http://stackoverflow.com/a/38829952/267540 – e4c5 Aug 10 '16 at 10:08
  • Some sensible code indentation help, then at least we can see what your code is doing – RiggsFolly Aug 10 '16 at 10:11
  • If you think about what `mysqli_real_escape_string` does you should not be surprised that a PDF file get at least subtily altered by running it through that function – RiggsFolly Aug 10 '16 at 10:14
  • Normally files that you store on the database (not necessarily a great idea in the first place) get converted to BASE64 before storing on the database and then converted back from BASE64 when you retrieve them – RiggsFolly Aug 10 '16 at 10:15
  • And does exist some way how to load the pdf file back without alterations? – Erik Aug 10 '16 at 10:35

0 Answers0