php image blob wont show - php

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));

Related

Can't display medium size pdf blob from database

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.

Export MySql table to CSV?

So, I have searched most of the answers here on stack and google and anywhere I could think of. There are plenty of answers indeed, but none have the structure I need.
Al my code looks like this:
$sql = "SELECT * FROM users WHERE user_level = '$level' ORDER BY user_username DESC";
if ($stmt = $this->connect->prepare($sql)) {
$stmt->bind_result($id);
$stmt->execute();
while ($row = $stmt->fetch()) {
$stmt->bind_result($id);
$users[] = $id;
}
$stmt->close();
$length[] = sizeof($users);
} else {
$error = true;
$message['error'] = true;
$message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
return json_encode($message);
}
I'm using mysqli and stmt in all of my code, so I would like to keep it like this all the way.
So, I understand that I cannot have the CSV file where I have my action button to download it. But the thing is that my action button is part of a form, so I guess that instead of $_GET on the page I have the CSV I will have $_POST.
And my question, how do I loop through all database ( this needs to be depending on a column, a level ) and take all that data organized in a CSV file and than download it ? But this needs to be as the structure I have for my functions, I don't want to use db_query("SELECT * FROM {loreal_salons}"); per say or other like that.
Use the following :
// Setup the headers to force download of CSV
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
// loop your records here and output as comma separated
echo $row['col1'].",".$row['col3'].",".$row['col3']."\n";
If you want to loop over all the database, I think the key for what you want to do is :
SHOW TABLES - http://dev.mysql.com/doc/refman/4.1/en/show-tables.html
.. to loop in all the tables
SHOW COLUMN - http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
.. to loop in all the column of a specific table

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']);
}

Save image URLs in MySQL?

I actually have a few questions here: My end goal is to write a script that will automatically display all the images that i have saved inside my database(If i add new images to my database(image URLs), each time i refresh the page i would like those "new" images to be instantly displayed as well).
What is the proper way to save an image URL inside MySQL? Currently i set my input type to VARCHAR; is that okay for image URLs?
Also, at the moment i'm working with WAMP server just to test how the site is working; so i put an image inside the www folder(within the same folder as my php script) and inside the database table i simply put the URL as follows: image.png is this the correct way to enter an image URL inside my database?
What is the best way to display these images in a sequence? The following code is what i have so far:(the image widths will take up about 70% of the page so the images will not be next to each other; they will be in a column form.)
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
for($count = 0; $count < $num; $count++)
{
//output the rows one by one(the actual images, not the URLs)
mysql_fetch_row($result);
echo("<br/>");
}
?>
I don't know if i should be using mysql_fetch_row in there..
I want my images to have some space in between; i was thinking the best way to accomplish that would be to add a "br" tag at the end of my loop so that every time a new image is displayed, a line break will be added to the end of the page.. Is that the best way to do it?
Thanks a bunch in advance!
To your first question, yes. To your second, also yes, if all your images are stored in the same directory. Mostly it's a matter of preference though.
Your for loop should look like this:
for($count = 0; $count < $num; $count++) {
$row = mysql_fetch_assoc($result);
echo "<img src='". htmlspecialchars($row["image"]) ."' alt='image' />";
}
br tags would probably be a bad idea. Set the images' display property to block in your CSS file. There are plenty of CSS manuals online.
With
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
you do some things twice. You do not want $query to be the result of a mysql_query() call and then apply mysql_query() again.
In this case, the second call would happen with a resource object instead of a string - you got informed about it. By putting "" around, you turn it into a string again, but one which doesn't make sense to mysql.
To verify that, try to put or die(mysql_error()) to the problematic calls.
And to fix that, you can try
$query = "SELECT * FROM tablename";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
BTW: you don't need $num when you replace the for loop with
while ($row = mysql_fetch_row($result))
// do stuff with $row
}
I've done a previous project based on image storage in a SQL database. the best way to store the images would be as a link, ie, '/stored_images/imagefilename.png'. When you need to reference the images just get the images into a while loop for each row in the table.
ie.
to get the images
<?php
$query = mysql_query("SELECT * FROM tablename");
while ($row = mysql_fetch_array($query)) {
echo '<img src="' . $row['column of url storage in SQL'] . '" />';
}
That will output all the images in the database, just change 'column of url storage in SQL' with the actual column name that you store in the SQL DB. also replace 'tablename' in the SQL query with the name of the table the images are being stored in.

correct way to upload image to database

i know some of you are going to say that this isnt the correct way but im on a tight deadline to finish an application and as of now i cant go back and modify the code to store the images in a directory.
now that thats cleared
the question i had is i inserted an image into the database by typing this.
(dont mind the class security call, all that is doing is a few checks if the data is valid)
$filename = $security->secure($_FILES['imgschool']['name']);
$tmpname = $security->secure($_FILES['imgschool']['tmp_name']);
$imgsize = $security->secure($_FILES['imgschool']['size']);
$imgtype = $security->secure($_FILES['imgschool']['type']);
$school = $security->secure($_POST['school']);
//begin upload
if($imgsize > 0) {
$handle = fopen($tmpname, "r");
$content = fread($handle, filesize($tmpname));
$content = addslashes($content);
//code to add all this to database
}
the variable $content is the image and all its getting is the addslashes. i remember someone once mentioning to do it with something called base64 but i can barely recall how it was written.
this is how i am calling the image from the database
aside from all the queries and whatnot
this is the main part that is calling the image
header("Content-length: ".$imgsize);
header("Content-type: ".$imgtype);
header("Content-Disposition: attachment; filename=".$imgname);
print $row['img'];
the problem i am having is that instead of the image showing. the url is only showing, so in this case i only see this
http://localhost/admin/school-catalog.php?page=gallery&id=4
when opening the page to view the image with the correct params set in the url.
for those that wanted to see the query that is being done to save the image and so forth
i copied the whole section
//save image to db
if(isset($_POST['btnupload'])) {
$filename = $security->secure($_FILES['imgschool']['name']);
$tmpname = $security->secure($_FILES['imgschool']['tmp_name']);
$imgsize = $security->secure($_FILES['imgschool']['size']);
$imgtype = $security->secure($_FILES['imgschool']['type']);
$school = $security->secure($_POST['school']);
//begin upload
if($imgsize > 0) {
$handle = fopen($tmpname, "r");
$content = fread($handle, filesize($tmpname));
$content = base64_encode($content);
}
$save = mysql_query("insert into tbl_schoolgallery(id,hash,img,imgtype,imgsize) values(null,'$school','$content','$imgtype','$imgsize')") or die(mysql_error());
header("Location: school-catalog.php?page=school_gallery");
}
//call image from db
$query = mysql_query("select * from $tbl where id = '$id'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
$imgtypeget = explode("/", $row['imgtype']);
$imgname = "img.".$imgtypeget[1];
$imgtype = $row['imgtype'];
$imgsize = $row['imgsize'];
header("Content-length: ".$imgsize);
header("Content-type: ".$imgtype);
print base64_decode($row['img']);
print $row['img'];
}
Using addslashes is extremely incorrect. Depending on whether your column is a TEXT field or a BLOB field, you should use Base64 or mysql_real_escape_string.
Using Base64 isn't that hard; you may as well use that way. Just replace addslashes with base64_encode and echo the image with base64_decode.
There's a bit easier way to write the whole thing, for that matter:
// begin upload
if ($imgsize > 0)
{
$content = file_get_content($tmpname);
$content = base64_encode($content);
}
And then to output you really only need to do
header("Content-type: ".$imgtype);
echo base64_decode($img);
If the column is a BLOB, however, you can directly use mysql_real_escape_string:
// begin upload
if ($imgsize > 0)
{
$content = file_get_content($tmpname);
$content = mysql_real_escape_string($content);
}
And then:
header("Content-type: ".$imgtype);
echo $img;
Although judging from your current symptoms, I'm guessing you also have a bug relating to how your image is being stored and recalled from the database, and I'd need to see that part of the code where you make the queries to insert and read from the database before I could help you fix that part.
Your current code seems mostly fine. A few issues:
print base64_decode($row['img']);
print $row['img'];
You probably meant to get rid of the second row. Also, you should use echo instead of print; everyone uses it, it can be slighty faster sometimes, and print doesn't really have any benefit other than returning a value:
echo base64_decode($row['img']);
$security->secure() appears to be some sort of sanitization function. Just use mysql_real_escape_string() - that's the one you're supposed to use. Except $imgsize; you might want to use intval() on that one since you know it's supposed to be an integer.
Also here:
$query = mysql_query("select * from $tbl where id = '$id'") or die(mysql_error());
You name the table tbl_schoolgallery a few rows above that. I assume $tbl == 'tbl_schoolgallery', but for consistency, you should either use $tbl in both places or tbl_schoolgallery in both places.
Also, replace that while with an if - your code would cause trouble if it ever loops more than once, anyway.

Categories