Displaying an image through a database php - php

I've been trying my head at this for ages, check every possible place on Google,
and sometimes I feel brain dead by just doing this.
I'm doing this for the fun of it but I am stuck on this particular aspect of displaying an image from a MySQL database using BLOB.
As far as I know I think I am uploading the image correctly, but whenever I try to display the image, it ends up just giving me the default image icon and the name of the image, Then when I inspect source, it comes up with gibberish for the image.
Can someone please tell me what I'm doing wrong?
show_profile.php
<html>
<body>
View Records
Logout
<div id="body_show">
<link href="show_profile.css" rel="stylesheet" type="text/css">
<div id="image" class="image" style="width: 152px; height:152px;">
<?php
include('database_connection.php');
if(session_id() ==""){
session_start();
}
$username = $_SESSION['myusername'];
$query = "SELECT * FROM $dImage_table WHERE username='$username' and imageID = (SELECT MAX(imageID) FROM $dImage_table WHERE username='$username')";
$result=mysqli_query($DBConn, $query);
if(!$result){
$message = "<p>
There was an error with the query.<br />\n" .
"The error was " .
htmlspecialchars(mysqli_error($DBConn), ENT_QUOTES) .
".<br />\nThe query was '" .
htmlspecialchars($query, ENT_QUOTES ) .
"'</P>\n";
}
else if (!mysqli_num_rows($result)){
$message = "<p>Cannot find Image in the database.</p>\n";
}
else{
while($report = mysqli_fetch_assoc($result)){
$imageData = $report['image'];
$imageName = $report['imageName'];
$imageType = $report['imageType'];
$imageID = $report['imageID'];
//echo "<img src="'data:image;base64,'.$imageData."' alt='Image'/>";
//echo "<img src=data:$imageType;base64,base64_encode($imageData) alt=$imageName width=152px height=152px/>";
echo '<img src="data:'.$imageType.';base64,'. base64_encode($imageData).'" alt="'.$imageName.'" width="152px" height="152px" />';
//echo "</br>";
}
//echo $imageData;
}
?>
</div>
<div class="form_body">
<form id="form_body" action="pic_uploader.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload">
</form>
<div>
<?php
//echo $message;
?>
</div>
</body>
pic_uploader.php
<?php
include('database_connection.php');
session_start();
if(isset($_POST['submit']))
{
$username = $_SESSION['myusername'];
$imageName = mysqli_real_escape_string($DBConn, $_FILES["image"]["name"]);
$imageData = mysqli_real_escape_string($DBConn, file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysqli_real_escape_string($DBConn, $_FILES["image"]["type"]);
$imageData= base64_encode($imageData);
if(!substr($imageType,0,4) == "image")
{
$message = "<p>Only Images are allowed!</p>";
include 'show_profile.php';
}
else{
$query = 'INSERT INTO dImage_table (username, imageID, imageName, imageType, image)
VALUES("'.$username.'",
"'. "" .'",
"'.$imageName.'",
"'.$imageType.'",
"'.$imageData.'")';
if(!mysqli_query($DBConn, $query))
{
$message = "<p>
There was an error uploading the image.<br />\n" .
"The error was " .
htmlspecialchars(mysqli_error($DBConn), ENT_QUOTES) .
".<br />\nThe query was '" .
htmlspecialchars($query, ENT_QUOTES ) .
"'</P>\n";
}
else
{
$message = "<p>Image uploaded</p>";
include 'show_profile.php';
}
}
}
?>
Thanks for your input

Upload the image to a web server and store the url of the image, never seen anyone store the image directly into a mysql database. Here's a simple tutorial on how to upload files: http://www.w3schools.com/php/php_file_upload.asp

Related

need to change file path with its id in database

Hi i have a code which is uploading file and saving its path in database. Now i want to change its path to its corresponding id with which it is saving in database i.e i have uploaded an image and its id is '4' in database and its file path should also be 4. and if i upload an other image and if its id is 5 then in its file path column there should also be 5 and so on. I have searched for a while but i'm not able to find the proper answer. Kindly help me here.
Here is my code
directory-image.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>image in directory</title>
</head>
<body>
<form method="post" action="directory-imagedatabase.php" enctype="multipart/form-data">
<label>Choose File to Upload:</label><br />
<input type="hidden" name="id" />
<input type="file" name="uploadimage" /><br />
<input type="submit" value="upload" id="upload" />
</form>
</body>
</html>
directory-imagedatabase.php
<?php
$target_Folder = 'images/';
$uid = $_POST['id'];
$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
$file_name = $_FILES['uploadimage']['name'];
if(file_exists('officework/php-startup/images/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
$con=mysqli_connect("localhost","root","sal123","test"); //Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO directoryimage (id,image, image_name)
VALUES ('','$target_Folder$file_name','$file_name') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully in the database";
echo '<br />';
mysqli_close($con);
// Move the file into UPLOAD folder
move_uploaded_file( $_FILES['uploadimage']['tmp_name'], $target_Path );
echo "File Uploaded <br />";
echo 'File Successfully Uploaded to: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
}
?>
Get the record's insert ID $id = mysqli_insert_id($con) after the INSERT
Get file extension: $ext = preg_replace("/\.(gif|jpg|etc)$/", ".$1", $file_name);
Rename the file with rename() rename("$target_Folder$file_name", $id . $ext);
Update the record with something like $sql = "UPDATE directoryimage SET image = CONCAT('{$target_Folder}', id, '{$ext}') WHERE id = $id";

No image is shown in PHP from MySqL

I am trying to display an image from my php page by saving the image in the database [MySql] and when I retrieve it it did't show me the image.
However, I can see the image when I click on it in MySql, but it is not shown in the php file.
Images Table:
id INT
image BLOB
index.php
<html>
<head>
<title>Uploade an image</title>
</head>
<body>
<form action="test_image.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Uploade">
</form>
<?php
mysql_connect("", "", "")
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db("test")
or die("<p>Error selecting the database: " . mysql_error() . "</p>");
// file propoerties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image.";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_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 Images (image) VALUES ('$image')"))
echo "Problem uploading image.";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded <p /> Your image: <p /> <img width='500' height='500' src=getimage.php?id=$lastid>";
}
}
}
?>
</body>
</html>
getimage.php
<?php
mysql_connect("", "", "")
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db("test")
or die("<p>Error selecting the database: " . mysql_error() . "</p>");
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM Images WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
I can upload the image but I can't retrieve it!!
Thank you,
you need to use img html element to view the image
for example
src here is where you are saving your image file
<img src="images/yoursavedimagenameindatabase" width="" height="">
Then you can view your saved images in view
$path="images/.$image['image']."
echo '<img width="100" height="66" src="'.$path.'" />';

Can't retrieve images from DB

I built a simple form for an image upload into the DB along with a description. The image and description are stored on the database but I am having a hard time retrieving/rendering (?) the images. I presume that the db connection is ok due to I can actually upload things. I will below leave you with the code and some print screens:
The table:
upload.php
<form action="imageUpload.php" method="post" enctype="multipart/form-data">
<label for="userFile">Upload your file: </label>
<input type="file" size="40" name="userFile" id="userFile"/><br />
<br />
<label for="altText">Description of image</label>
<textarea class="ckeditor" name="altText" id="altText"/></textarea><br />
<br />
<input type="submit" class="pdf" value="Save!" />
</form>
imageUpload.php
<?php
if ( !isset($_FILES['userFile']['type']) ) {
die('<p><strong>Du har inte laddat upp någon bild!</strong></p></body></html>');
}
?>
Your image:<br /><br />
Temporary name: <?php echo $_FILES['userFile']['tmp_name'] ?><br />
Original name: <?php echo $_FILES['userFile']['name'] ?><br />
Size: <?php echo $_FILES['userFile']['size'] ?> bytes<br />
Type: <?php echo $_FILES['userFile']['type'] ?></p>
<?php
require '../scripts/common.php';
// Validate uploaded image file
if ( !preg_match( '/gif|png|x-png|jpeg/', $_FILES['userFile']['type']) ) {
die('<p>Bara gif, png eller jpg/jpeg filer är accepterade!</p></body></html>');
} else if ( strlen($_POST['altText']) < 9 ) {
die('<p>Please write more then 9 characters!</p></body></html>');
} else if ( $_FILES['userFile']['size'] > 5000000 ) {
die('<p>Your image is too big!</p></body></html>');
// Connect to database
} else if ( !($link=mysql_connect($host, $username, $password)) ) {
die('<p>Could not connect to DB</p></body></html>');
} else if ( !(mysql_select_db($dbname)) ) {
die('<p>Error when connecting to DB</p></body></html>');
// Copy image file into a variable
} else if ( !($handle = fopen ($_FILES['userFile']['tmp_name'], "r")) ) {
die('<p>Could not open temp file!!</p></body></html>');
} else if ( !($image = fread ($handle, filesize($_FILES['userFile']['tmp_name']))) ) {
die('<p>Error when reading the temp file!</p></body></html>');
} else {
fclose ($handle);
// Commit image to the database
$image = mysql_real_escape_string($image);
$alt = htmlentities($_POST['altText']);
$query = 'INSERT INTO image (type,name,alt,img) VALUES ("' . $_FILES['userFile']['type'] . '","' . $_FILES['userFile']['name'] . '","' . $alt . '","' . $image . '")';
if ( !(mysql_query($query,$link)) ) {
die('<p>Could not save info on the DB!</p></body></html>');
} else {
die('<p>Your info has been saved!</p></body></html>');
}
}
?>
getImage.php
<?php
require '../scripts/common.php';
$link = mysql_connect($host, $username, $password);
mysql_select_db($dbname);
$query = 'SELECT type,img FROM image WHERE id="' . $_GET['id'] . '"';
$result = mysql_query($query,$link);
$row = mysql_fetch_assoc($result);
header('Content-Type: ' . $row['type']);
echo html_entity_decode($row['img']);
?>
showimage.php
<?php
require '../scripts/common.php';
if ( !($link=mysql_connect($host, $username, $password)) ) {
die('<p>Kunde inte koppla med databasen!</p></body></html>');
} else if ( !(mysql_select_db($dbname)) ) {
die('<p>Fel att läsa databasen!</p></body></html>');
} else {
$query = "SELECT id,name,alt FROM image";
if ( !($result = mysql_query($query,$link)) ) {
die('<p>Kunde inte läsa databasen!</p></body></html>');
} else {
for ( $i = 0 ; $i < mysql_num_rows($result) ; $i++ ) {
$row = mysql_fetch_assoc($result);
echo '<article class="span12 post">
<div class="mask3 span3">
<img src="getImage.php?id=' . $row['id'] . '" alt="' . $row['alt'] . '" title="' . $row['name'] .'"/>
</div>
<div class="inside">
<div class="span8 entry-content">
<div class="span12">
' . $row['alt'] . '
</div>
</div>
</div>
</article>';
}
}
}
?>
Final result at showimage.php:
So, any suggestions on how do I make the images appear?
I suspect there's an issue with "updload" of the image. The call to mysql_real_escape_string is scanning for "characters" that need to be escaped, and inserting a backslash character before any "unsafe" character.
If $image is binary data (I don't see any base64 or hexadecimal encoding/decoding going on), I suspect that you don't really want to alter the binary data.
Given what you have already got, converting the binary data into hex format might work for the INSERT (as long as the length of the SQL text doesn't exceed max_allowed_packet).
... , img ) VALUES ( ... , x'FFD8FFE00004A464946000102' )
Another option is to use the MySQL LOAD_FILE function, to read in the contents of a file located on the MySQL server host. Again, max_allowed_packet limits the size of the file that can be loaded this way.
... , img ) VALUES ( ... , LOAD_FILE('/tmp/img.jpg') )
If the images are blobs or plain binary data use data URIS- https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
Wild guesses here. Trying to figure it out and provide information that might help solve the problem.
I have never put binary files into MySQL (so I'm not aware of escaping requirements with BLOBs, if any?????)
(Make sure it's not a CSS thing. :-))
<?php
require '../scripts/common.php';
$link = mysql_connect($host, $username, $password);
mysql_select_db($dbname);
$query = 'SELECT type,img FROM image WHERE id="' . $_GET['id'] . '"';
$result = mysql_query($query,$link);
$row = mysql_fetch_assoc($result);
header('Content-Type: ' . $row['type']);
echo html_entity_decode($row['img']); //Is enough being echoed here?
?>
// html_entity_decode() on a BLOB? [PHP Manual: html_entity_decode()][1]
<div class="mask3 span3">
<img src="getImage.php?id=' . $row['id'] . '" alt="' . $row['alt'] . '" title="' . $row['name'] .'"/>
</div>
If enough is being echoed in the last line of getImage.php. Is the file name required at all?
If you are using the <base> HTML tag, you might not have to specify the full url.
If inside getImage.php you echo row['img'] instead of html_entity_decode($row['img']); I believe it will work.

How to store image link in database php/mysql

I'm trying to allow an admin upload pictures of products in to the database, but I only want to store the link/url of the picture in the database and then store the uploaded file in a folder.
This is what I've got so far, and I keep getting "Sorry there was a problem uploading your file".
Here is the PHP code:
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, "$targetFolder" . $imgName)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
and the HTML form:
<form id="product_form" name="product_form" enctype="multipart/form-data" action="inventory_list.php" method="post">
<label for="product_image">Product Image*:</label> <input type="file" name="product_image"id="product_image"/>
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form
Use Sql Query Below.
$sql = "INSERT INTO products(`product_name`,`product_model`,`product_price`,`product_width`,`product_height`,`product_weight`,`product_quantity`,`product_category`,`product_subcategory`,`product_image`,`product_description`,`date_added`) VALUES('".$product_name."','".$product_model."','".$product_price."','".$product_width."','".$product_height."','".$product_weight."','".$product_quantity."', '".$product_category."', '".$product_subcategory."', '".$imgName."', '".$product_description."','".date("Y-m-d H:i:s")."')";
Also Change below line for upload image $imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); to $imgData = $_FILES["product_image"]["tmp_name"];
Try this Hope this helps.Not tested
<form id="product_form" name="product_form" enctype="multipart/form-data" method="post" action="" >
<label for="product_image">Product Image*:</label> <input type="file" name="product_image" id="product_image" />
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form>
PHP code :
<?php
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, $targetFolder)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
?>
First of all in HTML form action="post" is incorrect, the action attribute should contain a path. The method attribute should contain post or get like this: method="get" or method="post".

How to save uploaded image in database

I need help in writing this code to upload and save uploaded image in data base.
File 1:
<?php
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
<iframeid="upload_target"name="upload_target"src="#"style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
File 2:
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path="my/";
$result = 0;
$name=$_FILES['myfile']['name'];
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
list($width, $height, $type, $attr) = getimagesize($target_path);
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;
$result = 1;
}
// sleep(1);
$link=mysql_connect('localhost','root','');
if(!$link)
{die('you cannot connect to database...');}
$db=mysql_select_db('final');
if(!$db)die('smile');
if (isset($_FILES['myfile']) && $_FILES['myfile']['size'] > 0) {
// define the posted file into variables
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$type = $_FILES['myfile']['type'];
$size = $_FILES['myfile']['size'];
// if your server has magic quotes turned off, add slashes manually
//if(!get_magic_quotes_gpc()){
//$name = addslashes($name);
//}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, filesize($tmp_name));
$content = addslashes($content);
fclose($extract);
// connect to the database
// the query that will add this to the database
$s=mysql_query("SET NAMES 'utf8'");
$sql = "INSERT INTO `final`.`products` (`Productcode`, `Productname`, `Price`,`Descriptionofgood`, `image`) VALUES ('','','','','".$target_path."') WHERE `products`.`Productcode`='1371' ";
$results = mysql_query($sql);
if(!$result)die('not');
}
?>
Technically, if it is a small project.
You should not store images files in "Database" ; rather only their link (you may not even need that). Image or any media files are stored on server along with your other files (html,css,php). Of course, you need to put them on a dedicated folder for it.
The reason for not storing on database : because they are meant for data retrieval only and more importantly they are of smaller size (bigger sizes do exist, i am speaking in case of a small project which requires least possible resources. Storing media files on database is just not efficient.
Looking at your code, i can tell you are trying to store the files on your server.
They have used a very simple script for uploading here . Try it on your localhost before trying on a server.
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) is incorrect.
It should be if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))
Remove the #.
I have created three page for it
index.php (Form for uplad image)
upload.php (Save the image in upload folder and its path in database)
3.showimage.php (Show the images from database)
Database Structure
id int(4) auto increment - image varchar(100) - image_name varchar(50)
here is the code:
index.php
<form method="post" action="upload.php" enctype="multipart/form-data">
<label>Choose File to Upload:</label><br />
<input type="hidden" name="id" />
<input type="file" name="uploadimage" /><br />
<input type="submit" value="upload" />
</form>
uplad.php
<?php
$target_Folder = "upload/";
$uid = $_POST['id'];
$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
$file_name = $_FILES['uploadimage']['name'];
if(file_exists('upload/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
con=mysqli_connect("localhost","user_name","password","database_name"); //Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO image (id,image, image_name)
VALUES ('','$target_Folder$file_name','$file_name') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully in the database";
echo '<br />';
mysqli_close($con);
// Move the file into UPLOAD folder
move_uploaded_file( $_FILES['uploadimage']['tmp_name'], $target_Path );
echo "File Uploaded <br />";
echo 'File Successfully Uploaded to: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
?>
Show Image
showimage.php
<?php
$con=mysqli_connect("localhost","user_name","password","test"); //Change it if required
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM image " );
while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['image'] . '" width="200" />';
echo'<br /><br />';
}
mysqli_close($con);
?>

Categories