Can't display medium size pdf blob from database - php

I'm trying to display my PDFs stored in a MariaDB database on my XAMPP server via HTML and PHP
Code:
<object data="data:application/pdf;base64,<?php echo base64_encode($this->view_data[0]["test"]); ?>" type="application/pdf" style="height:100%;width:100%"></object>
It works for PDFs with a size of 500kB but for PDFs with the larger size, the Page stays blank.
Is there any configuration I have to do in my XAMPP conf files? I tried to increase pretty much all of them nothing seems to work
Edit:
I'm using "SELECT test from PDF WHERE testID = 1" with the function
public function dbQuery($query, $params = []){ $stmt = $this->connect()->prepare($query); $stmt->execute($params); if (explode(' ',$query)[0] == "SELECT"){ $result = $stmt->fetchAll(); $this->close($this); return $result; } else{ $this->close($this); return $stmt->fetchAll(); } $this->close($this); }
to populate the var $this->view_data so the PDF is stored in $this->view_data[0]["test"]
It works fine for everything blobsize <= 500kB. I tried setting the PDO MYSQL_ATTR_MAX_BUFFER_SIZE but the variable is not even initialized.

I found the answer. It was because I didn't use PDOs statements for LOBs (large objects)
With
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname.";charset=utf8",$dbuser, $dbpwd);
$stmt = $db->prepare("SELECT test FROM PDFs WHERE testID=?");
$stmt->execute(array($_GET['testID']));
$stmt->bindColumn(1, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-Type: application/pdf");
fpassthru($lob);
It works.

Related

PHP: CSV import into MYSQL is always less than the actual amount of rows in the CSV file?

This is a very strange issue that I have and I don't understand what's causing it.
Basically, the issue is that I have a simple upload function in my PHP that uploads a CSV file and then imports each row into the MYSQL database.
Now, the issue is that I have around 200+ rows in my CSV file but when i upload and import it into the MYSQL using my PHP page, I only get around 158 of them imported and I don't get any errors at all either so i don't understand what's causing this.
I have another CSV file that has around 300+ rows in it and when I upload/import this CSV file, i get around 270 rows imported into MYSQL.
This is like the import function is always short a few rows and I don't understand it at all.
This is my PHP import code:
error_reporting(-1);
ini_set('display_errors', 'On');
if (isset($_POST['UP'])) {
include "config/connect.php";
$imp= $_FILES["csv"]["name"];
move_uploaded_file($_FILES["csv"]["tmp_name"],"imports/$imp");
// path where your CSV file is located
////////////////////////////////////////////////////////
define('CSV_PATH','');
// Name of your CSV file
$csv_file = CSV_PATH . "imports/".$imp."";
$i = 0;
set_time_limit(10000);
$fp = fopen("imports/".$imp."", "r");
while( !feof($fp) ) {
if( !$line = fgetcsv($fp, 1000, ',', '"')) {
continue;
}
$sql0 = "INSERT INTO `myTable`(`column1`) VALUES('".$line[0]."')";
$query0 = mysqli_query($db_conx, $sql0);
}
fclose($fp);
printf("<script>location.href='mypage.php'</script>");
exit();
}
Using direct import into MYSQL is out of question due to security issues/hole..
Could someone please advice on this issue?
Any help would be appreciated.
To get around quoting issues, you want to use prepared statements with bind_param.
Procedural style:
$stmt = mysqli_prepare($db_conx, "INSERT INTO `myTable`(`column1`) VALUES(?)");
mysqli_stmt_bind_param($stmt, 's', $line[0] );
mysqli_stmt_execute($stmt);
Object-oriented style:
$stmt = $mysqli->prepare("INSERT INTO `myTable`(`column1`) VALUES(?)");
$stmt->bind_param('s', $line[0]);
$stmt->execute();
Per the docs, use s for strings, i for integers, and d for doubles/decimals.

Cannot display image from DB2 in php pdo from blob format

we are working on HRM system where user profile pictures are displayed. We have a working Java version which take blob from db2 and after processing displays it. It works fine. Now we are trying to do the same stuff with php using pdo.
Here is the code we use to get the job done but it does not work.
BLOB is in format of
FFD8FFE000104A46494600010201012C012C0000FFE1129345786966000049492A000800000009000F01 ....
Code:
static function arr('SELECT * FROM TABLE WHERE ID_PERSON= 22')
{
global $conn;
$n = count($conn->query($sql)->fetchAll());
if ($n > 0) {
$q = $conn->query($sql);
if (!$q) {
$rs = $conn->errorInfo();
}
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$rs[]=$row;
}
} else {
$rs = 'empty';
}
return $rs;
}
in page it is located as like this
<img src="data:image/jpeg;base64,<?=base64_encode(hex2bin($rs['IMAGE_COLUMN']))?>"
and it is view like this (almost similar like the java result but it is not and does not work).
src="data:image/jpeg;base64, /9j/4AAQSkZJRgABAgEBLAEsAAD/4RKTRXhpZgAASUkqAAgAAAAJAA8BAgAGAAAAegAAABABAgAWAAAAgAAAABIBAwABAAAAAQAAABoBBQABAAAAlgAAABsBBQABAAAAngAAACgBAwABAAAAAgAAADEBAgAbAAAApgAAADIBAgAHYCAACdggUAAQAAAH4CAAAiiAMAAQAAAAMAAAAniAMAAQAAAPQBAAAwiAMAAQAAAAIAAAAyiAQAAQAAAPQBAAAAkAcABAAAADAyMzADkAIAFAAAAIYCAAAEkAIAFAAAAJoCAAABkgoAAQAAAK4CA ....
We are might be wrong on hex2bin but it is taken advise from Stack Overflow and its result much more like the working one. and without it is is not looking like base64 at all.

php image blob wont show

So I am trying to show an image from my mysql database. The image is saved as a blob format. I made seperate php file for fetching the image. I then call this file from where I want to show the image like so:
<img src="image.php?id=3" />
This is the file that fetches the image:
<?php
require 'scripts/connect.php';
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$q = $db->prepare("SELECT image FROM products WHERE id = '$id'");
$q->execute();
$data = $q->fetch();
header("content-type: image/jpeg");
echo $data["image"];
}
?>
But when I try and run this code no image shows up. Instead I get this annoying broken link image thing:
http://i.imgur.com/NQOPSAf.png
Your code doesn't do what you expect.
Try to change
$q = $db->prepare("SELECT image FROM products WHERE id = '$id'");
in - if id field is numeric one; if isn't, add single quote -
$q = $db->prepare("SELECT image FROM products WHERE id = $id");
Your example didn't work as you were passing to query $id placeholder and not his value (you dind't concatenated it)
Of course with that method you're not save by SQL Injection at all, so you should use pepared statement that way
$q = $db->prepare("SELECT image FROM products WHERE id = :id");
$q->execute(Array(":id" => $id));
Edit
As OP told me that $data['image']; is a bitstream, I will suggest to use something like:
echo '<img src="data:image/jpg;base64,'. base64_encode($data['image']). '" alt='imagename'>;
or if your echo goes directly into src attribute:
echo 'data:image/jpg;base64,'. base64_encode($data['image'])
Try to replace
header("content-type: image/jpeg");
with
header("content-type: image/png");
Try,
$query = $db->prepare("SELECT image FROM products WHERE id = :id");
$query->execute(array(":id" => $id));
$data = $q->fetch();
For serving the image, use
$mime = pathinfo($data['image'], PATHINFO_EXTENSION);
header('Content-Type: '.$mime);
ob_clean();
flush();
readfile($data['image']);
Note:
readfile() needs the image path to where the images are stored.
if you are use PHP >= 5.4, $query->execute([":id" => $id]);
can be used instead of
$query->execute(array(":id" => $id));

read and write image from or to database

I try to show an image stored in a database. I wrote it with
$image = file_get_contents($testPfad);
$dateigroesse = filesize($testPfad);
$arrData = unpack("H*hex", $image);
$data_string = "0x".$arrData['hex'];
$sql = "INSERT INTO EHS.dbo.T_Signaturen (UnterschriftsDateiName,UnterschriftsBild,Dateigroesse,terminID) VALUES (
'".$unterschriftsFileName."',
CONVERT(varbinary(max),'$data_string'),
'".$dateigroesse."',
'384_234')";
echo '<hr>'.$sql;
insert($sql);
With this code I output the image.
header("Content-type: image/jpeg");
$query = "SELECT Dateigroesse, CONVERT(varchar(max), UnterschriftsBild) as content_data FROM EHS.dbo.T_Signaturen WHERE ID = '10'";
$result = query($query);
$content = $result[1]["content_data"];
$filesize = $result[1]["Dateigroesse"];
$content = substr ($content, 2); // entfernt 0x
$content = pack("H*", $content);
print $content;
Everything works fine but only a part of the image is shown. I reduced the image size from 20kb to 2kb and much more is shown so I think ANYWHERE the binary data is cut. The Database Column is a varbinary(max)
Please let us not discuss wether it is rational to store blob in databases :) :)
The solution was to increase the max accepted string length of odbc in php.ini. It was set to 4069 chars
did you try to define your column as BLOB (up to 2 GB)?
are you sure, that the complete image is stored (maybe that function is wrong)

Display an image (tinyblob) stored in a database with php

I try to read image from database (blob) but i have problem becouse i don't know mime type of image. I have only tinyblob.
Can i read image and save it back to my hard disk?
The best solution is to store the mime-type in the DB at the same time you're inserting the image into the blob field. Otherwise you're going to have to the following EACH TIME the image is retrieved:
$image = $row['imageblob']; // $row = result row from DB query.
$finfo = new finfo(FILEINFO_MIME);
$mime_type = $finfo->buffer($image);
This gets to be expensive very quickly on a busy system, so best do the determination ONCE and then store that result.
Relevant PHP docs here.
Why not store the images on the hard disk all the time, and store in the Database a relative link based on a known directory?
Here's some code that I have used to get a logo (blob) from a mysql database
<img src="data:image/png;base64,<?php echo base64_encode($MyClass->getLogo())?>" alt="Logo" width="233" height="65" />
And the getLogo() function
public function getLogo()
{
if ($this->getId())
$query = "SELECT `logo` FROM Logos WHERE `logo_id` = '{$this->getId()}' LIMIT 1";
else
$query = "SELECT `logo` FROM Logos WHERE `logo_id` = '1' LIMIT 1";
$result = mysql_query($query);
if ($result)
$row = mysql_fetch_array($result);
else
return NULL;
return ($row['logo']);
}

Categories