How to display an BLOB image stored in MySql database? - php

I am trying to display the last 5 images uploaded to my "store" table in MySql.
I'm a complete noob to PHP and databases and i've been reading a lot on how to do this but no luck.
I can store and display pictures one at a time but i'd like to be able to have a gallery of sorts to show the last 5 uploaded.
any advice or help would be greatly appreciated thanks!
p.s. I know it frowned upon to store pictures to a database like this but this project is just for practice.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Project One</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
<form>
<p />
<?php
//connect to database
(connect to server)
(select correct DB)
//file properties
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "please select an image.";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = $_FILES['image']['name'];
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE)
echo "That's not an image.";
else
{
if (!$insert = mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image')"))
echo "Problem Uploading Image.";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded. <p />Your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
<p />
<p />
Go to Gallery
</body>
</html>
get.php
<?php
//connect to database
(connect to server)
(select correct DB)
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>

This is what I used when I wanted to do something like that... a long time ago! =P
$sql = "SELECT image FROM table WHERE cond ORDER BY xxxx DESC LIMIT 5";
$result = mysqli_query($db,$sql);
while($arraySomething = mysqli_fetch_array($result))
{
echo "<img src='php/imgView.php?imgId=".$arraySomething."' />";
}

I try the first approach with header('content-type: image/jpeg'); but end up with image not shown. After a few google through website I found the solution which I can display image from database to my page
try this:
mysql_connect("localhost","root","")or die("Cannot connect to database"); //keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56"; // manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/>'

mysql_connect("localhost","root","")or die("Cannot connect to database");
//keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56";
// manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/> width="xxxx" height="xxxx"';
Add the height and width also

You can also use this function
//Retrieve image from database and display it on html webpage
function displayImageFromDatabase(){
//use global keyword to declare conn inside a function
global $conn;
$sqlselectimageFromDb = "SELECT * FROM `imageuploadphpmysqlblob` ";
$dataFromDb = mysqli_query($conn, $sqlselectimageFromDb);
while ($row = mysqli_fetch_assoc($dataFromDb)) {
echo '<img height="250px" width="250px" src=data:image;base64,'.$row['image'].'/>';
}
Insert it into mysql database like this :
$image = $_FILES['imagefile']['tmp_name'];
$name = $_FILES['imagefile']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
references : https://mauricemutetingundi.blogspot.com/2019/04/how-to-upload-blob-image-to-mysql.html

Related

Display BLOB from mySQL with php

After I managed it to insert blobs into my db I'm trying to Display a BLOB from MySQL.
This is the getImage.php:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "root");
mysql_select_db("user_auth_tutorial");
$sql = "SELECT image FROM testblob WHERE image_id='$id''";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['image'];
?>
Here the HTML:
<img src="getImage.php?id=1" width="200" height="200" />
This is the content of my db:
Unfortunately Dev-Tools throw an internal server 500 Error.
Browser-Output:
Can anybody tell me what I do wrong?
Thank you so much!
try this
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'"/>';

Broken Image when uploading it to MySQL Database

I am trying to store images into a path and then upload them into my database. The DB is called "store" and the table I'm using is called "images" containing 3 fields: id, name (varchar), image (longblob). The form is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload an Image</title>
</head>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="262144000" />
<p>File:</p>
<input type="file" name="image" accept="image/jpeg" accept="image/jpg" accept="image/png" accept="image/gif">
<input type="submit" value="Upload" name="submit" />
</form>
</body>
</html>
The upload_file.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file)){
echo "<p>Please select an image.</p>";
} else {
//$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "<p>Sorry, this is not an image.</p>";
} else {
echo "<p>File is an image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')")){
echo "<p>Problem uploading image:".mysql_error()."</p>";
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
error_reporting(-1);
?>
And get.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
$id = $_REQUEST['id'];
$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_array($image);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
?>
The images are uploaded, but are not shown. Instead, I get a broken image icon, and I don't understand why. Can someone help me??
Try to solve this problem step by step
This process can be identified as three parts and split up quickly. The HTML form, the PHP upload and saving to database process, and the loading from database process.
Try echoing the image data before inserting it into the database to see if the data is actually correct.
Update the database and see if the data is inserted there.
Load the image data from the database and echo it to see if it loads it correctly.
Try the full script.
This is just an example checklist. But you can change this and add more steps to it.
Also, please consider updating to MySQLi. You are using deprecated functions which could lead to security issues. Many information sources regarding this subject can be found on the web.
Correct the get.php code with this code
<?php
//Connect to database
$conn = mysql_connect("localhost", "tester", "");
if (!$conn) {
die("Could not connect to MySQL");
}
if (!mysql_select_db("tester")) {
die("Could not open database:" . mysql_error());
}
$id = $_REQUEST['id'];
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
You have to change the database name and user whit your own
These are the parts that i have changed:
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
echo base64_decode($image);

php ,mysql image is not displaying from database

image is not displaying from the database it show just showing broken image
<?php
$con = mysql_connect('localhost', 'root', ''); //Update hostname
mysql_select_db("postad", $con); //Update database name
$query = "SELECT path1 FROM img_tbl";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result);
$photo = $row['path1'];
echo "<center><img src=$photo alt=Profile Photo>";
?>
$photo is path right
then try this
echo '<center><img src='.$photo.'alt="Profile Photo"></center>';
Moving from the comments, this is the fix you need:
echo '<center><img src= '.$photo.' alt="Profile Photo"></center>';
Change second last line with this
echo '<center><img src="'.$photo.'" alt="Profile Photo"></center>';
This will work if $photo path is correct...

Struggling to display blob image with php

I am building a simple website, I want to allow the users to upload and change their avatars. At present I have been able to upload images to a mysql database, stored as blobs with the code as follows:
//connected to DB, userID fetched
$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());
When I download the files from phpmyadmin after upload they are saved as .bin files, but can be viewed normally. I'm not sure if this is correct or not.
My code to display the images is as follows:
HTML:
<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>
PHP:
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
header('Content-type: image/jpeg');
$row = mysql_fetch_object($result);
echo $row['image_data'];
}
I am unsure if I am attempting to display the image in the correct way, any help (corrections/alternative solutions) would be greatly appreciated :)
You can do this :
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
$content = mysql_result($result,0,"file_content");
$name = mysql_result($result,0,"file_name");
$type = mysql_result($result,0,"file_type");
$size = mysql_result($result,0,"file_size");
header("Content-type: $type");
echo $content
}
Note : You should have these column in you table where you save your BLOB data
file_name = for save filename
$_FILES['file']['name']
file_type = for save file type
$_FILES['file']['type']
file_size = for save file size
$_FILES['file']['size']
You select this
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
and refer to not selected column
echo $row['image_data'];

Image upload in a database directory

i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line
upload.php
<?php
include("connecton.php");
$_SESSION['username']="kyle";
$username = $_SESSION['username'];
if($_POST['submit'])
{
//get file attribute
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if($name)
{
//start upload process
$location = "avatars/$name";
move_uploaded_file($tmp_name,$location);
$query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");
die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
}
else
die("Please select a file");
}
echo "Welcome, ".$username."!<p>";
echo "Upload Your Image:
<form action='upload.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>
</form>
";
?>
view.php
<?php
include("connecton.php");
$username = $_SESSION['username'];
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($query)==0)
die ("User not found");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
echo "<img src='$location' width='100' height='100'>";
}
?>
a) You do not check if the upload succeeded. At least do something like:
if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
... upload went ok
}
b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.
c) You do not check of the move_uploaded_file() succeeded:
if (!move_uploaded_file(...)) {
die("Move failed!")
}
d) You do not check if the database query succeeded:
$stmt = mysql_query(...)
if ($stmt === FALSE) {
die("MySQL query failed: " . mysql_error());
}
e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.
f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.
First php statement of both of upload.php and view.php should be this:
session_start();

Categories