How to Store .Pdf Files into MySQL as Blobs Using PHP

How to insert a pdf file in a MySQL database and then read it in php?

You need to

  1. Store the data in a TEXT column in MySQL, not BLOB, because a base64 string is text, not binary data.

  2. Query that field from your database to get the base64 data

  3. Decode the base64 data to get the original binary data.

  4. Send that data for download, setting the appropriate headers for your browser to understand that it's a file download rather than a web page.

You seem to have the SQL part sorted now, judging by the update to your questions, so here I'll just show a simpler way to download the data, without needing to write a file to the server disk first (which you'd then need to clean up later).

$filedata = $row['label']; //get base64 data from query result
$decoded = base64_decode($filedata); //decode base64 to binary

//set suitable HTTP response headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//output the binary file data in the body of the response
echo $decoded;
exit;

Storing and retrieving PDF File in Mysql Database in PHP

$value = file_get_contents('yourpdf.pdf')

Then record $value in your database.

Can't store a .pdf file in a blob in mySQL

According to this comment you should not pass the blob directly in bind_param, but with send_long_data.

From the documentation of send_long_data here's an example:

$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();

Save PDF as a blob in a database using PHP?

$fp = fopen($fileLocation, 'r');
$content = fread($fp, filesize($fileLocation));
$content = addslashes($content);
fclose($fp);

You can save the $content to blob field in mysql

How do I download a pdf blob file from database?

Try adding this header line of code between your header and echo statement :

header('Content-Type:'.$result->mime);
header("Content-Disposition: inline; filename=filename.pdf");
echo $result->pdf_file;

You can set Content-Disposition: to attachment if you want it to download the file instead.

read pdf content from BLOB in MySQL

As mentioned by @Shadow:

Mediumblob is up to 16MB only. Base64 drastically increases the size of the data, so there may be some data truncation even if the original binary size is below 16MB. Pls include the code that stores and retrieves the files from the database.

i modified the field to LONGBLOB and now it seems to work fine! :-)



Related Topics



Leave a reply



Submit