I am trying to retrieve an image from mongoDB and display it in web browser. But it is not working. Here is the code which I am using for insertion and retrieval
Code to upload:
<?php
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
if(isset($_REQUEST['formsubmit']))
{
$m = new MongoClient();
$coll = $m->test;
$gridFS = $coll->getGridFS();
$tag = $_REQUEST['username'];
$gridFS->storeUpload('pic',array("tag"=>$tag));
echo 'File Uploaded Successfully';
$m->close();
}
?>
<!-- image and any file uploaded in mongodb -->
<html>
<head> Upload Image</head>
<body>
<!--The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form. -->
<form method="POST" enctype="multipart/form-data">
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
<label for="pic">Please upload a profile picture:</label>
<input type="file" name="pic" id="pic" />
<input type="submit" value="Register" name="formsubmit"/>
</form>
</body>
</html>
Code to retrieve image and display in browser:
<?php
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
$m = new MongoClient();
$coll = $m->test;
$gridFS = $coll->getGridFS();
?>
<html>
<head>Displaying Image</head>
<body>
<?php
header('content-type: image/jpg');
echo '<img src=' . $gridFS->findOne(array("tag"=>"temp123"))->getBytes() .'>'. '</img>';
?>
</body>
</html>
Could anyone please help me out ??
Thank you
Really thankful for this wonderful opportunity to help you.
First of all..GridFS is using for saving files that more than 16mb size.You ain't mention on that question.
The below codes are for saving images less than 16mb.
***************** Image insertion**************
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["pic"]["name"]); //Image:<input type="file" id="pic" name="pic">
$tag = $_REQUEST['username'];
$m = new MongoClient();
$db = $m->test; //mongo db name
$collection = $db->storeUpload; //collection name
//-----------converting into mongobinary data----------------
$document = array( "user_name" => $tag,"image"=>new MongoBinData(file_get_contents($target_file)));
//-----------------------------------------------------------
if($collection->save($document)) // saving into collection
{
echo "One record successfully inserted";
}
else
{
echo "Insertion failed";
}
******************Image Retrieving******************
public function show()
{
$m=new MongoClient();
$db=$m->test;
$collection=$db->storeUpload;
$record = $collection->find();
foreach ($record as $data)
{
$imagebody = $data["image"]->bin;
$base64 = base64_encode($imagebody);
?>
<img src="data:png;base64,<?php echo $base64 ?>"/>
<?php
}
}
}
?>
Hope you will try this.Enjoy coding.Stay Blessed.
Related
I'm new to database designing and I'm working on an upload formula.
In my example I have 3 input buttons. The upload of all selected file to my uploads folder works fine, but my problem is, only the first of all selected files gets inserted in my database.
Here is my code:
$db = mysqli_connect("localhost", "root", "", "xy");
if (isset($_POST['upload_docs'])) {
for($mi = 0; $mi < count($_FILES['sel_file']['tmp_name']); $mi++) {
$doc = $_FILES['sel_doc']['name'][$mi];
$tmp_doc = $_FILES['sel_doc']['tmp_name'][$mi];
$target = "doc_uploads/". basename($doc);
if (move_uploaded_file($$tmp_doc, $target)) {
echo "Upload successfully!";
}
else {
echo "Upload failed!";
}
}
}
$sql_f = "INSERT INTO docs (doc_file) VALUES ('$doc')";
mysqli_query($db, $sql_f);
<form method="POST" action="upload.php" enctype="multipart/form-data">
<div>
<input type="file" name="sel_doc[]" multiple="multiple">
<input type="file" name="sel_doc[]" multiple="multiple">
<input type="file" name="sel_doc[]" multiple="multiple">
</div>
<div id="sel_button">
<button type="submit" name="upload_docs">upload</button>
</div>
</form>
I try upload image to mysql database and display it along with the description of image using php. After i upload the image and display it , a broken image was displayed but the description of the image was displayed without any error. How can I solve this problem ? Appreciate your help
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="try.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
This is my result :
You are storing it in the DB without the images directory. You either need to store it with that, or always remember to call it that way in your image calls.
echo "<img src='images/".$row['image']."'>";
or make your the record you are writing the same as the filesystem location.
$image = 'images/' . $_FILES['image']['name'];
Note you are open to SQL injections and file inclusion injections with this code.
try this
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["image"]["name"]);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
//#move_uploaded_file($_FILES['image']['tmp_name'], $target_path)
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target_path))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
I am using the following form to create a photo album, it submits the data to a processing script which then deals with the files and enters data into the database.
THIS IS THE SUBMIT FORM :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create New Album</title>
</head>
<body>
<p>Create New Album</p>
<form action="createnewalbumsubmit.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="hidden" value="<?php echo substr(md5(time() * rand()),0,10); ?>" name="albumid" id="albumid" />
<input type="hidden" value="<?php echo date("Y-m-d"); ?>" name="datecreated" id="datecreated" />
<input type="hidden" value="yes" name="isalbum" id="isalbum" />
<p>
<label for="albumname">Album Name</label>
<input type="text" name="albumname" id="albumname" />
</p>
<p>
<label for="albumthumbnail">Album Thumbnail Image</label>
<input type="file" name="albumthumbnail" id="albumthumbnail" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
</body>
</html>
THIS IS THE DATA PROCESSING SCRIPT, IT IS USING THE VEROT UPLOAD CLASS FOR DEALING WITH THE UPLOADED FILE AND THEN MYSQLI TO ADD DETAILS TO THE DATABASE :
<?php include("connect.php"); ?>
<?php
// Posted Data
if(isset($_POST['albumid'])){
$albumid = $_POST['albumid'];};
if(isset($_POST['datecreated'])){
$datecreated = $_POST['datecreated'];};
if(isset($_POST['isalbum'])){
$isalbum = $_POST['isalbum'];};
if(isset($_POST['albumname'])){
$albumname = $_POST['albumname'];};
//
require_once 'uploadclass/class.upload.php';
$file = new Upload($_FILES['albumthumbnail']);
if ($file->uploaded) {
// save uploaded image with a new name,
// resized to 100px wide
$albumthumbnail = substr(md5(time() * rand()),0,10);
$file->file_new_name_body = $albumthumbnail;
$file->image_resize = true;
$file->image_convert = 'jpg';
$file->image_x = 100;
$file->image_ratio_y = true;
$file->Process('albums/'.$albumid.'/thumbnail/');
$filename = $file->file_dst_name;
if ($file->processed) {
echo 'image renamed, resized x=100
and converted to jpg';
$file->Clean();
} else {
echo 'error : ' . $file->error;
}
}
mysqli_query($db,"INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
?>
The problem I am having is that when I create a new record TWO records are being created in the database, one blank record with nothing at all in it and one valid record with all of the details of the added album in it.
It's because you're not checking if the form is being posted. Each time you land on the page it will run:
mysqli_query($db, "INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
This is why you're getting a blank record. You need to surround your submit code with if (!empty($_POST)) { } as such:
<?php
include ("connect.php");
if (!empty($_POST)) {
// Posted Data
if (isset($_POST['albumid'])) {
$albumid = $_POST['albumid'];
};
if (isset($_POST['datecreated'])) {
$datecreated = $_POST['datecreated'];
};
if (isset($_POST['isalbum'])) {
$isalbum = $_POST['isalbum'];
};
if (isset($_POST['albumname'])) {
$albumname = $_POST['albumname'];
};
//
require_once 'uploadclass/class.upload.php';
$file = new Upload($_FILES['albumthumbnail']);
if ($file -> uploaded) {
// save uploaded image with a new name,
// resized to 100px wide
$albumthumbnail = substr(md5(time() * rand()), 0, 10);
$file -> file_new_name_body = $albumthumbnail;
$file -> image_resize = true;
$file -> image_convert = 'jpg';
$file -> image_x = 100;
$file -> image_ratio_y = true;
$file -> Process('albums/' . $albumid . '/thumbnail/');
$filename = $file -> file_dst_name;
if ($file -> processed) {
echo 'image renamed, resized x=100
and converted to jpg';
$file -> Clean();
} else {
echo 'error : ' . $file -> error;
}
}
mysqli_query($db, "INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
}
?>
I am making a gallery that uses a MySQL database (yeah I know it's a bad practice but it's the requirement for the moment.) I can upload multiple images but I'm having trouble displaying all images stored inside the database. The FORM allows five images to be uploaded. Then the user must proceed to another page where all the images in database (including the ones uploaded recently) will be displayed together with the description of the images. I have code already but the one that will work on the display is not working or I think is wrong.
Here is the form code:
<html>
<head>
<title> Upload image</title>
</head>
<body>
<div align="center">
<form action="fUpload.php" method="POST" enctype="multipart/form-data">
All forms must be filled. <br />
File: <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="file" name="image[]"/> <input type="text" name="imageDescription[]" size="30" /> <br />
<input type="submit" value="Upload image" />
</form>
</div>
</body>
</html>
Here is the script that would upload:
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
And finally the one that should display:
<html>
<body>
</body>
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM images WHERE id = $id");
while($datum = mysql_fetch_array($image, MYSQL_ASSOC))
{
printf("Description %s $image = $image['image'];
header("Content-type: image/jpeg");
}
mysql_close();
?>
Your help is much appreciated. I need it badly to move on.
From what i understand from your post is that uploading and storing isn't a problem, but showing the images is. That's probably because you're using vars that are not set, so no results kan be found in the database. If i misunderstood let me know.
<?php
// No ID
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
?>
Also look at what Prof83 says. Ignore my post if your script works with just one image.
Last but not least, if you're using different filetypes, also echo the correct MIME format in the header.
Update
I combined both answers.
Edit your loop:
<?php
while($row = mysql_fetch_assoc($image))
{
echo '<img src="img.php?id='.$row["id"].'">';
}
?>
Create a page name img.php
<?php
$query = mysql_query("SELECT image FROM images WHERE id = ".$_GET['id']);
$row = mysql_fetch_assoc($query);
header("Content-type: image/jpeg");
echo $row['image'];
?>
Ok you can't display multiple images within a image/jpeg page...
You're telling the browser that the page is image/jpeg (in other words, the page is AN IMAGE) but you're echoing out multiple image data
You should rather use the gallery page to show all images like this:
<?php
// $images = result from database of all image rows
foreach ($images as $img) echo '<img src="img.php?id='.$img["id"].'">';
?>
and in img.php:
// Load the image data for id in $_GET['id'];
header("Content-type: image/jpeg");
echo $data;
i have this page for upload:
<?php
require ('incs/db.php');
require_once ('incs/funcs.php');
?>
<?php
if (array_key_exists('upload', $_POST)) {
$directory = str_replace(basename($_SERVER['PHP_SELF']),'',$_SERVER['PHP_SELF']);
$uploadHandler = $_SERVER['DOCUMENT_ROOT']. $directory . 'images/';
// $uploadHandler = "echtitipi".$_SERVER['HTTP_HOST']. '/images/';
$max_file_size = 30000;
define('UPLOAD_DIR', $uploadHandler);
$ext= end(explode(".", $_FILES['image']['name']));
$name = rand(1111111,9999999).'.'.$ext;
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadHandler. $name))
{
$upload = true;
$title = $_POST ['title'];
$sql = "INSERT INTO photo (id, keyword, photoName)
VALUES ('','$title','$name')
";
$result = mysql_query ( $sql, $con );
}
else
{
$upload = false;
$msg = 'Cant Upload!';
}
}
?>
<?php
include ('incs/header.php');
?>
<?php
getUrlQuery();
?>
<script language="javascript">
<!--
function pick(symbol, path) {
if (window.opener && !window.opener.closed)
window.opener.document.form.img.value = symbol;
window.opener.document.form.imgbox.src = path;
window.close();
}
// -->
</script>
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">
Tanım:
</label>
<input type="text" name="title" id="title" />
<label for="image">
Upload image:
</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<?php
if($upload == true)
{
echo "<a hrf(because spam!)=\"javascript:pick('$name','images/$name')\"><im(g) src=\"images/$name\" border=\"0\" alt=\"use\"></a>";
}
?>
<?php
include ('incs/footer.php');
?>
`
this upload image to curretnt root's images folder. My current folder is admin:
root/admin/images
root/images
when i use
$uploadHandler = "http://".$_SERVER['HTTP_HOST']. '/images/';
script doesnot work.
<?php
if($upload == true)
{
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
}
?>
the image couldnot add to editor. I guess There is a problem with javascript.
what is wrong in script
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
change into
echo "<img src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\">";
I guess this will help...
Im sorry for bad dictation because i cant write the right script because sending errors(link and images)
above code uploaded code to
/www/admin/images
and save information to database and add image to tinymce editor. But I want to upload code to:
www/images
when I use :
$uploadHandler = $_SERVER['DOCUMENT_ROOT'].'/images/';
and
"<img src=\"images/$name\" border=\"0\" alt=\"use\">"
the image couldnot add to editor. This is my problem.