I've trimmed my code down to the bare minimum to try to find why I cannot display any image that I upload & store via PHP into MySQL. If anyone can point out my error(s) I'd be most grateful.
On execution, the browser reports that the image cannot be displayed as it contains errors.
However, the image uploads & displays fine in other databases running in this same environment.
I've checked that the database holds a blob after upload.
I guess I'm missing something obvious.
Upload form..
<body>
<form enctype="multipart/form-data" action="imagetestprocess.php" method="post">
<input type="file" name="image">
<input type="submit" value="Submit">
</form>
Form handler..
<?php
include("../mylibrary/login.php");
login();
$imagefile = file_get_contents($_FILES['image']['tmp_name']);
$imagefile = mysql_real_escape_string($imagefile);
$query="UPDATE pieces SET image_full='$imagefile' WHERE assetno='1'";
$result = mysql_query($query);
?>
Image displayer..
<?php
include("../mylibrary/login.php");
login();
echo "<body>";
echo "before";
echo "<img src=\"showimage.php\" alt=\"showimage\">";
echo "after";
?>
called function...
<?php
include("../mylibrary/login.php");
login();
$query = "select * from pieces where assetno='1'";
$result=mysql_query($query);
$row=mysql_fetch_array($result, MYSQL_ASSOC);
$image=$row['image_full'];
header("Content-type: image/jpeg");
echo $image;
?>
change the image_full field type to MEDIUMBLOB / BLOB
user this $image = chunk_split(base64_encode(file_get_contents("image.jpg")));
instead of $imagefile = file_get_contents($_FILES['image']['tmp_name']);
and in show image function use image as below.
header("Content-type: image/jpeg");
echo base64_decode($image);
use mysql_escape_string or addslashes and clear your browser cache to see if it works
If the above solutions does not work for you.
Try increasing the length of the field in database.
if still it does not work,
You can check if the image format is RGB or CMYK.
format shoud be RGB to see on screen.
To make it sure you can try opening the same image file in browser.
I think it has something to do with your database encoding. some encoding does not support binary data.
If you cannot change the encoding, maybe you css base64 encode the data before saving and decode it when displaying. only thing is base64 will increase the size by 3.
Related
I have read numerous articles on stackoverflow and google regarding file upload and show directly in/from MYSQL BLOB column. I donot need to upload file anywhere because only one file is involved in my complete project and that is the logo file to be updated by the user.
Although I wanted to do the things with Codeigniter Upload library, but i couldn't complete the code so I was trying simple PHP solution, but it hasnot worked either.
Below is my code.
Code for Upload Form:
<?php echo form_open_multipart('UpdateCompanyInfo'); ?>
<div class="form-group">
<label>Logo</label>
<input type="file" class="form-control" name="logo">
[200 px (width)x200px (height)]
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update Logo</button>
</div>
<?php echo form_close(); ?>
Code for Upload:
$check = getimagesize($_FILES["logo"]["tmp_name"]);
if($check !== false)
{
if($check[0]=="200" && $check[1]=="200" )
{
$image = $_FILES['logo']['tmp_name'];
$imageFileType = strtolower(pathinfo($_FILES['logo']['name'],PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
return '<div class="alert alert-danger">'.$imageFileType.' Logo file of only jpg/png/jpeg type is acceptable.</div>';
}
$imgContent = addslashes(file_get_contents($image));
if($this->db->update("company", array('logo'=>$imgContent)))
{
return '<div class="alert alert-success">Logo has been updated successfully.</div>';
}
else
{
return '<div class="alert alert-danger">Error 101. Failed to update the logo.</div>';
}
}
else
return '<div class="alert alert-danger">Logo file of only 200px X 200px is acceptable.</div>';
}
Code to show the Image in View
echo '<img src="data:image/png;base64,'.base64_encode($companyinfo[0]->logo).'"/>';
I uploaded the png file, so I have used data:image/png
On inspecting the image element in view, I get the following output:
<img src="data:image/png;base64,iVBORw0KGgpcMFwwXDAN ....... v6/IDhCwtLWDE56vdo6CwCC07dMeva1dhgIGnEBikg7xODG0Pq+m61z8bC4Vqpzxpq6d8BhQK7Q1+rte/oyhK61mIAoGRznxWpiYmb8jaleunKEotrSaXy1Xb1lnxXhXvSAGgKtXBetZJOQEAIQkBAQAhCQEAIQkBACEJA8P7xP2GoiDrA7B2BXDBcMFwwXDBJRU5ErkJggg==">
All articles over internet are showing this solution, but why it is not working at my end?
You need to save image as base64_encode in database. Change your code as below line while uploading:
$imgContent = base64_encode(file_get_contents($image));
and when you need to show image, you just need to put content. No need to encode again. As below:
echo '<img src="data:image/png;base64,'.$companyinfo[0]->logo.'"/>';
Hope it helps you.
After trying the suggestions of #dnFer I tried using stripslashes while displaying the image. Things worked fine.
echo '<img src="data:image/png;base64,'.base64_encode(stripslashes($companyinfo[0]->logo)).'"/>';
But I have a Question. Somewhere I read: "As I was reading this I saw the problem was stripslashes(). Since the data is binary it might contain arbitrary characters that are equal to slashes so it will remove them. "
Will this be a problem? And is my data still safe after stripping away the slashes?
Short answer:
Change
$imgContent = addslashes(file_get_contents($image));
to
$imgContent = file_get_contents($image);
Long answer:
When applying addslashes(), the binary data of the image changes when it contains one or more single quote ('), double quote ("), backslash (\) or NUL (the NUL byte). It adds a backslash before those characters.
This is probably done to avoid SQL injection at the time prepared statements didn't exist or where rarely used.
Eg:
$imgContent = addslashes(file_get_contents($image));
$query = mysql_query ("insert into imageTable values ("INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$imgContent}', '{$image_name}')"));
//Do Stuff like reading the image date from the database...
$imgContent = stripslashes($imgContent);
echo '<img src="data:image/png;base64,' . base64_encode($imgContent) . '"/>';
These days, not using prepared statements is bad practice and I suspect your database library makes use of it as well at the following line:
$this->db->update("company", array('logo'=>$imgContent));
Prepared statements (using mysqli or PDO) statements will prevent SQL injection, which make the use of addslashes() unnecessary.
Notes:
Make sure your database data field is large enough (TINYBLOB, BLOB,
MEDIUMBLOB, and LONGBLOB) to contain the complete image (data).
Do not store base64 encoded image data in the database as this data
is about 30% larger than the binary data.
Prefer to store images on the file server instead of the database, since storing lots of data can slow down the database server.
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
</form>
Php code upload.php
<?php
include_once 'dbconn.php';
$image = $_FILE['image'];
$name = $image['name'];
$tmpname = $image['tmp_name'];
$imgdestination = '../img/'.$name;
move_uploaded_file($tmpname, $imgdestination);
?>
Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end
I would like to know how to display an image stored in a database inside of a particular div using PHP code?
The code I used looks like that:
<form method="post">
<input type="button" name="show" value="show"/><br/>
<input type="image" id="image_show" name="img" value="img"/>
</post>
if(#$_POST['show'])
{
$sql="select imageData form images ORDER BY DESC";
$result=mysql_query($sql) or die('invalid query'.mysql_error());
//set header
header("Content-type:image/png");
echo mysql_result($result,0);
while( $row = mysql_fetch_row( $result ) )
{
echo "<img src='".$row[0]."'/>";
}
}
But it does not work. How can I solve this task?
You need to specify the name of the column you want to retrieve from your returned array (imageData in this case)
echo '<img src="'.$row['imageData'].'"/>";
Also, if dont need this line if you just want to show the image and now force the download:
//set header
header("Content-type:image/png");
It will throw you an error anyway as you are printing information before it with that form.
echo "<img src='".$row['imageData']."'/>";
If the data is embedded in the database as blob, use:
<img src="data:image/png;base64,ABC"/>
With 'ABC' is the image in base64.
Please see here for more information on data URL.
I am trying to make a simple file upload from php to mysql and downloading it back but i keep to seem on running into a problem, but I can't figure it out. The picture that I try to upload in this form creates some content in the blob column but on download widows viewer gives and error of no preview available
Here's the code for the form
<form enctype="multipart/form-data" method="post" action="upload.php">
Choose your file <input name="file" type="file">
<input type="submit" >
</form>
Here's the code for upload.php
include('connect.php');
$actualname=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$name = $_FILES['file']['tmp_name'];
$size = $_FILES['file']['size'];
$fresource=fopen($name,'r');
$content=fread($fresource,filesize($name));;
$content=addslashes($content);
fclose($fresource);
$query='INSERT INTO `files` (Name,Content,Type,Size) VALUES ("'.$actualname.'","'.$content.'","'.$type.'","'.$size.'")';
echo $query;
$var=mysql_query($query,$con);
and here's the code for download.php
include('connect.php');
$query='SELECT * FROM `files` WHERE ID="2"';
$res=mysql_query($query,$con);
$var=mysql_fetch_array($res);
header("Content-length: ".$var[4]);
header("Content-type: ".$var[3]);
header("Content-Disposition: attachment; filename=".$var[1]);
echo $var[1];
Any help would be much appreciated
The files table has the ID,Name,Content,Type,Size columns in the same order
DONT USE MYSQL_*
also addslashes() is a terrible and falible way to secure your code.
As it is the code is susceptible to SQL injection.
i'm assuming that your database is
id name content type size
so change the last line to
echo stripslashes($var[2]);
since
0 => id,
1 => name,
2 => content,
and you added slashes to the content... so now you need to remove em.
I am new to php and trying to upload an image file in mysql database using php.I tried various tutorial but it didnot work for me.
Code Snippet:-
<?php
//connect to database. Username and password need to be changed
mysql_connect("localhost", "root", "");
//Select database, database_name needs to be changed
mysql_select_db("yelldb");
if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>
<?php
}else{
//if the form hasn't been submitted then:
//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved
//into the database. The image is named after the persons IP address until it gets moved into the database
//get users IP
$ip=$_SERVER['REMOTE_ADDR'];
//don't continue if an image hasn't been uploaded
if (!empty($image)){
//copy the image to directory
copy($image, "./temporary/".$ip."");
//open the copied image, ready to encode into text to go into the database
$filename1 = "./temporary/".$_SERVER['REMOTE_ADDR'];
$fp1 = fopen($filename1, "r");
//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));
//close the file
fclose($fp1);
//encode the image into text
$encoded = chunk_split(base64_encode($contents1));
//insert information into the database
mysql_query("INSERT INTO servicelist (ImgData)"."VALUES ('$encoded')");
//delete the temporary file we made
//unlink($filename1);
}
}
?>
We don't save out the whole image in our database usually. We go through inserting the permanent of picture in our database. Use this php function
move_uploaded_file(file,newloc)
This will move from your temporary directory to permanent directory. Then, get path from there and insert that to the database.
Typically, you wouldn't save an entire image into an SQL database. Instead, you store the on disk path or some other 'pointer' to the actual file.
Change your code to read something like the following:
//don't continue if an image hasn't been uploaded
if (isset($_POST['image'])){
$image = $_POST['image'];
//copy the image to directory
$path = "/some/path";
move_uploaded_file($image,$path);
//store the name and path. PS: you will want to validate your input, and look
//at using prepared statements.
//Concentating values like this is NOT safe, or ideal
$location = $path . "/" . $image
mysql_query("INSERT INTO servicelist (ImgData) VALUES (" . $location . ")");
}
If however, you still wish to store the image in the SQL database, look into the blob storage type, not encoded text.
PHP move_uploaded_file