I would like to display an image stored in my database but I keep getting that error.
The image is stored in my database as longblob.
I upload it using this piece of code in upload.php:
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" />
<input type="submit" name="submit" value="UPLOAD" />
</form>
<?php
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
/*
* Insert image data into database
*/
//Insert image content into database
$insert = $pdo->query("UPDATE users SET image='".$imgContent."'"."WHERE id_user = ".$posts[0]->get_id());
if ($insert) {
echo "File uploaded successfully.";
} else {
echo "File upload failed, please try again.";
}
} else {
echo "Please select an image file to upload.";
}
}
?>
Then I try to display it in getImage.php:
<?php
$id = $_GET['id'];
$query = $pdo->prepare('SELECT * FROM users WHERE username LIKE :us');
$query->bindValue(':us', $_SESSION['login'], PDO::PARAM_STR);
$query->execute();
$user = $query->fetchAll(PDO::FETCH_CLASS, "User");
header ('Content-Type: image/png');
echo $user[0]->get_image();
?>
When I go however to /getImage.php?id=1, I have the error
The image cannot be displayed because it contains errors
What am I doing wrong?
Solved: I added ob_end_clean(); before the header and it worked.
I have a very weird problem in my system. I already create a system to upload the image to the database and display it. The problem is, the image is successfully uploaded but, it will return the message "Failed to upload!". Then, the picture that had been uploaded does not display. Below is my code:
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
//Convert image to base64
$encoded_image = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']));
$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$sql -> execute();
//$results = $sql -> fetchAll(PDO::FETCH_OBJ);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($sql->rowCount() > 1 ) {
echo "Status : Uploaded";
$last_insert_id = $conn-> lastInsertId();
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$sql = $conn->prepare($query);
$sql -> execute();
if($sql->rowCount($sql) == 1 ) {
//$row = mysqli_fetch_object($result);
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo "<br><br>";
echo '<img src="'.$row->encoded_image.'" width="250">';
}
}
}
}
?>
</div>
</body>
Can someone help me? Thanks!
you doing some thing wrong first you encoded the image when store in database so you must decode it again, and the src in tag get a url not image content just echo the content like this:
header('Content-type: image/jpeg');
echo base64_decode($row->encoded_image);
or
<img src="data:image/png;base64,'.$row->encoded_image.'" width="250">
but at all, store images in database is not a good option, your database become too heavy and can't respond fast and get too memory you can just store the image name in database and move the file form special place in your server the you can show like this.
echo '<img src="specialRoot/'.$row->image_name.'" width="250">';
Store images in folder..
I have created uploads folder in root, you can create folder at anywhere and write your path while fetching the image..
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
$name = $_FILES['uploadFile']['name'];
$target_dir = "uploads/"; //give path of your folder where images are stored.
$target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Check extension
if( in_array($imageFileType,$allowed_extensions) ){
//Convert image to base64
$image_base64 = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']) );
$encoded_image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
//$encoded_image = base64_encode($_FILES['uploadFile']['tmp_name']);
//$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$result = $sql -> execute();
move_uploaded_file($_FILES['uploadFile']['tmp_name'],$target_dir.$name);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($result == 1) {
echo "Status : Uploaded";
$last_insert_id = $conn->insert_id;
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
echo '<img src="'.$row['encoded_image'].'" width="250">';
}
}
}
?>
</div>
</body>
So I have this code. I am working with uploading image and I want it to be displayed after the user has uploaded it. Help me with my code please, just a PHP newbie here. :(
connect.php
<?php
$servername = "localhost";
$user = "root";
$password = "12345";
$db = "demo";
$con = mysqli_connect($servername, $user, $password, $db);
if (!$con) {
die('Could not connect: ' .mysql_error());
}
?>
try.php here
<?php include 'connect.php'; ?>
<?php
if (isset($image)) {
$errors = array();
$imageName = $_FILES['photoUpload']['name'];
$imageSize = $_FILES['photoUpload']['size'];
$imageType = $_FILES['photoUpload']['type'];
$imageTmp = $_FILES['photoUpload']['tmp_name'];
$imageExt = strtolower(end(explode('.', $imageName)));
$expensions = array("jpeg", "jpg", "png");
if(in_array($imageExt, $expensions)===false) {
$errors[] = "Extensions not allowed. Only JPEG, JPG, PNG";
}
if($imageSize > 2097152) {
$errors[] = "File size must not exceed 2MB";
} else { print_r($errors); }
}
?>
<div class="col-md-4">
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="photoUpload"><br><br>
<input type="submit" name="submit" value="SUBMIT"/>
<ul>
<li>Sent File: <?php echo $imageName; ?></li>
<li>File Size: <?php echo $imageSize; ?></li>
</ul>
</form>
</div>
I know I lack something here like displaying it using echo and such. I also want it to be displayed in height & width = 200px; and border-radius: 50%;
Are you saving the name of it in your database?
If so, try this below
$id = $_SESSION['id'];
$sql = "SELECT image FROM user WHERE `id` = $id";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
//img tag fetching from folder 'images' - change to match the file it was uploaded to
echo "<img src='images/".$row['image']."' style='width:30%; height:30%;'>";
echo "</div>";
}
You will need to change the query to fit your code, but the idea should set you in the right direction.
I have made a code where you can choose an image from your computer and upload it to the database. For some reason, after I have uploaded it(it is uploaded in the database correctly), the image that is showned isnt the image I have uploaded but it is a little image showing that it cant get the image from the database. Can someone help me?? Here is the code:
index.php:
<?php
ob_start();
include_once('connect.php');
session_start();
?>
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form enctype="multipart/form-data" action="index.php" method="POST">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
//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 = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == false){
echo 'That is not an image';
}else{
if (!$insert = mysqli_query($con,"INSERT INTO uploading_image(name,image) VALUES('$image_name','$image')")){
echo 'Problem uploading image';
}else{
$lastid = mysqli_insert_id();
echo 'Image uploaded. <br>Your image:<br><img src="get.php? id='.$lastid.'">';
}
}
}
?>
</body>
</html>
$get.php:
<?php
include_once('connect.php');
$id = addslashes($_REQUEST['id']);
$image = mysqli_query($con,"SELECT * FROM uploading_image WHERE id='$id'");
$find_image = mysqli_query($row = mysqli_fetch_array($image));
$image_db = $row['image'];
header("Content-type: image/png");
echo $image_db;
?>
check the datatype for the field image in the database. It should be blob or longblob. replace the following code
$find_image = mysqli_query($row = mysqli_fetch_array($image));
with this.
$find_image = mysqli_query($row = mysqli_fetch_assoc($image));
here is my error.i dont know why it is not working.i checked all the parts but i was unable to find the error.
Notice: Undefined index: image in C:\xampp\htdocs\Final\places\Ressave.php on line 27
here is my html code that pass the name of input:
<form class="form-horizontal" action="Ressave.php" method="POST" autocomplete="on">
<div class="well">
<legend>Photos</legend>
<div class="control-group">
<label class="control-label">Upload Photo: </label>
<div class="controls">
<input name="image" type="file" />
</div>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</form>
Ressave.php is here and can not recieve the name here,so the error occure.....
<?php
{ // Secure Connection Script
include('../Secure/dbConfig.php');
$dbSuccess = false;
$dbConnected = mysql_connect($db['hostname'],$db['username'],$db['password']);
if ($dbConnected) {
$dbSelected = mysql_select_db($db['database'],$dbConnected);
if ($dbSelected) {
$dbSuccess = true;
} else {
echo "DB Selection FAILed";
}
} else {
echo "MySQL Connection FAILed";
}
// END Secure Connection Script
}
if(! $dbConnected )
{
die('Could not connect: ' . mysql_error());
}
{ // File Properties
$file = $_FILES['image']['tmp_name']; //Error comes from here(here is the prob!)
if(!isset($file))
echo "Please Choose 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 is not an image.";
else
{
$lastid = mysql_insert_id();
echo "Image Uploaded.";
}
}
}
{ //join the post values into comma separated
$features = mysql_real_escape_string(implode(',', $_POST['features']));
$parking = mysql_real_escape_string(implode(',', $_POST['parking']));
$noise = mysql_real_escape_string(implode(',', $_POST['noise']));
$good_for = mysql_real_escape_string(implode(',', $_POST['good_for']));
$ambience = mysql_real_escape_string(implode(',', $_POST['ambience']));
$alcohol = mysql_real_escape_string(implode(',', $_POST['alcohol']));
}
$sql = "INSERT INTO prestaurant ( ResName, Rating, Food_serve, Features, Parking, noise, Good_For, Ambience, Alcohol, Addition_info, Name, Address1, Zipcode1, Address2, Zipcode2, Address3, Zipcode3, City, Mobile, phone1, phone2, phone3, phone4, Email1, Email2, Fax, Website, image)".
"VALUES ('$_POST[restaurant_name]','$_POST[star_rating]','$_POST[food_served]','$features','$parking','$noise','$good_for','$ambience','$alcohol','$_POST[description]','$_POST[name]','$_POST[address1]','$_POST[zipcode1]','$_POST[address2]','$_POST[zipcode2]','$_POST[address3]','$_POST[zipcode3]','$_POST[city]','$_POST[mobile]','$_POST[phone1]','$_POST[phone2]','$_POST[phone3]','$_POST[phone4]','$_POST[email1]','$_POST[email2]','$_POST[fax]','$_POST[url]','$image')";
mysql_select_db('place');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($dbConnected);
?>
If a file was not uploaded the $_FILES array will be empty. Specifically, if the file image was not uploaded, $_FILES['image'] will not be set.
So
$file = $_FILES['image']['tmp_name']; //Error comes from here(here is the prob!)
should be:
if(empty($_FILES) || !isset($_FILES['image']))
update
You will also have issues because you're missing the enctype attribute on your form:
<form class="form-horizontal" action="Ressave.php" method="POST" autocomplete="on" enctype="multipart/form-data">
In order to be able to process files in your form you need to add the enctype attribute.
<form method='POST' enctype='multipart/form-data' >
Hey i guess you have forgotten one important setting in form
enctype="multipart/form-data" this option is used when used with files eg image file etc
<form name="image" method="post" enctype="multipart/form-data">
Apart from that to extract the contents of the file you can use following options
$tmp_img_path = $_FILES['image']['tmp_name'];
$img_name = $_FILES['image']['name'];
to print all the content of a file use:
print_r($_POST['image']);
this is the code i have which successfully insert the data into mysql and retrieve from the DB.
"Index.PHP"
<html>
<head>
<title>PHP & MySQL: Upload an image</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>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("registrations") or die(mysql_error());
if(!isset($_FILES['image']))
{
echo 'Please select an image.';
}
else {
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
echo $_FILES['image']['tmp_name'];
$image_name = addslashes($_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 test_image 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>";
}
}
}
?>
</body>
</html>
this is get.PHP
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("registrations") or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM test_image WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
NOTE:- please changes your DB and table name accordingly..
Thanks,
Santanu