Davide Gualano Davide Gualano - 1 year ago 165
PHP Question

Save a PDF created with FPDF php library in a MySQL blob field

I need to create a pdf file with the fpdf library and save it in a blob field in my MySQL database.
The problem is, when I try to retrieve the file from the blob field and send it to the browser for the download, the donwloaded file is corrupted and does not display correctly.

The same pdf file is correctly displayed if I send it immediately to the browser without storing it in the db, so it seems some of the data gets corrupted when is inserted in the db.

My code is something like this:

$pdf = new MyPDF(); //class that extends FPDF and create te pdf file
$content = $pdf->Output("", "S"); //return the pdf file content as string
$sql = "insert into mytable(myblobfield) values('".addslashes($content)."')";

to store the pdf, and like this:

$sql = "select myblobfield from mytable where id = '1'";
$result = mysql_query($sql);
$rs = mysql_fetch_assoc($result);
$content = stripslashes($rs['myblobfield']);
header('Content-Type: application/pdf');
header("Content-Length: ".strlen(content));
header('Content-Disposition: attachment; filename=myfile.pdf');
print $content;

to send it to the browser for downloading.
What am I doing wrong?

If I change my code to:

$pdf = new MyPDF();
$pdf->Output(); //send the pdf to the browser

the file is correctly displayed, so I assume that is correctly generated and the problem is in the storing in the db.

Thanks in advance.

Answer Source

You shouldn't strip any (back)slashes. When you add them, they are used as escape characters in the query and do not appear in the field.

Try changing this

$content = stripslashes($rs['myblobfield']);

into this:

$content = $rs['myblobfield'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download