Ok so i uploaded images with code below but i dont know how to display it, i want to make gallery so all i want is to display all images on one page, if you could explain that would be helpfull too!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phplogin";
$connect = mysqli_connect($servername,$username,$password,$dbname);
$file = $_FILES['image']['tmp_name'];
$ime = $_POST['ime'];
if(!isset($file))
{
echo "Izaberite sliku";
}
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 "Niste izabrali dobru sliku";
}
else
{
if(!$insert = mysqli_query($connect,"INSERT INTO store VALUES ('','$image_name','$image','$ime')"))
{
echo "Problem sa postavljanjem slike";
}
else
{
//$lastid = mysqli_insert_id($connect);
// I WANT TO DISPLAY IMAGES HERE
//echo "Image uploaded.<p />Slika:<p /><img src=get.php>";
}
}
}
?>
This code is to get image but it only display last ID and i dont know how to make it display all images
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("databaseimage") or die(mysql_error());
$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;
?>
Save images as files instead of blobs. Store url to image in db as varchar
The html
<form role="form" class="form-inline" enctype="multipart/form-data" method="post" action="">
<div class="form-group">
<input type="file" class="form-control" name="image"/>
</div>
<input type="submit" name="upload" class="btn btn-success" value="Upload" />
</form>
php
define('UPLOAD_PATH','images/');
This is the constant for the path of the images. In this case its a folder named images in the same directory as the script you are working on
$errors = array();
function output_errors($errors){
$output=array();
foreach($errors as $error){
$output[]='<li>'.$error.'</li>';
}
return '<ul>'.implode('',$output).'</ul>';
}
if(isset($_POST['upload'])){
if(!empty($_FILES['image']['name'])){
$image=$_FILES['image']['name'];
$image_type=$_FILES['image']['type'];
$image_size=$_FILES['image']['size'];
if((($image_type=='image/gif') || ($image_type=='image/jpeg') || ($image_type=='image/png') || ($image_type=='image/pjpeg')) &&
($image_size>0) /*&& ($image_size<=MAX_FILE_SIZE)*/){
if($_FILES['image']['error']==0){
/*give each image a unique name*/
$image=microtime().$image;
/*move uploaded file to permanent folder*/
$target=UPLOAD_PATH.$image;
if(move_uploaded_file($_FILES['image']['tmp_name'],$target)){
if(mysqli_query($connect,"INSERT INTO images(`image`) VALUES ('$image')") ){
$message="Image was uploaded sucessfully";
}else{
$errors[]="Error,image was not uploaded successfully";
/*delete permanent file from server*/
#unlink(UPLOAD_PATH.$image);
}
}/*end of move uploaded file*/
}
}else{
$errors[]="File uploaded must be of type png, jpeg or gif";
/*delete temporary image file*/
#unlink($_FILES['image']['tmp_name']);
}/*end of image validation*/
}else{
$errors[]="Please select an image file";
}/*empty*/
}
if(!empty($errors))echo output_errors($errors);
if(!empty($message)) echo $message;
Your images table could appear like this
CREATE TABLE IF NOT EXISTS `images` (
`image_id` int(11) NOT NULL,
`image` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1;
To get an image from db, you could have a query that selects image from table images. To display image in html do
$queryImage=mysqli_query($connect,"SELECT `image` FROM images");
while($rowImage=mysqli_fetch_assoc($queryImage)){?>
<img src="<?php echo UPLOAD_PATH.$rowImage['image'] ;?>" style="width:250px; height:200px"/>
<?php
}/*end of while loop getting images*/?>
Related
I have a table named images. It has two columns id and image (varchar300). I have this code upload.php :
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
require_once('dbConnect.php');
$sql ="SELECT id FROM images ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png";
$actualpath = "/home/kinanday/public_html/$path";
$sql = "INSERT INTO images (image) VALUES ('$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
this is upload.html :
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button>Upload</button>
</form>
</body>
The problem is: it saves into my database but the image in my file manager in Cpanel is 0kb
I am using this code to integration to my android app which need an image with varchar type. So in my app does not show image anything because the image is 0KB.
Can anybody with your advance to fix my php. every answer is very helpful for me. Thanks in advance.
You need to use the $_FILES superglobal, as #Fred-ii- said.
but $image = $_FILES['image'] is a array, see the options for it here: http://php.net/manual/en/features.file-upload.post-method.php
Examples:
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_tmpname = $_FILES['image']['tmp_name']; // this is a temporary name that php uses on every upload he does.
$image_type = $_FILES['image']['type'];
$image_error = $_FILES['image']['error'];
I want to store image in database directly without storing it in a folder on my explorer. If possible than how? I am using php with mysql database to store image and i have define datatype LONGBLOB to store image in database. Below is my code:
<?php
$conn = mysqli_connect("localhost","root","")or die(mysqli_error($conn));
mysqli_select_db($conn,'image') or die(mysqli_error($conn));
if(isset($_REQUEST['submit'])){
$old = $_FILES['img']['tmp_name'];
$new = $_FILES['img']['name'];
move_uploaded_file($old,$new);
echo $sql = "INSERT INTO img(`img_name`) VALUES('$new')";
$exe = mysqli_query($conn,$sql);
if($exe){
echo "Image Uploaded Successfully....";
}
}
echo $query = "Select `img_name` from `img`";
$ex = mysqli_query($conn,$query);
?>
<html>
<body>
<form method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<div>
<input type="file" name="img"/>
</div>
<div>
<input type="submit" name="submit" value="Upload"/>
</div>
<?php
while($res = mysqli_fetch_array($ex)){
?>
<div>
<img height="50" width="50" src="<?php echo $res['img_name'];?>"/><br/>
</div>
<?php } ?>
</form>
</body>
</html>
You would need to convert the image into base64. something like this:
$path = $_FILES['img']['tmp_name'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
It'd be better to save it as a string rather than BLOB if possible. If it has to be a BLOB you'd have to convert the string and then convert it back when you're retrieving from the database. If you store it as a string, the image will even work with the base64 as the src of the image.
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
mysql_query ("insert into pix (mgdata) values ('".image."')");
And after delete uploaded image, image will be in DB
After you can send image from DB to browser
$gotten = #mysql_query("select * from pix order by pid desc limit 1");
if ($row = #mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>
I need to do a web page for a client to upload images to a data base and display them.
I am achieve to upload the images into a database, but I'm having trouble displaying them, but I can't work out why
Here is my code:
<!DOCTYPE html>
<head>
<body>
<form action="form.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("test" ) or die(mysql_error());
$file = $_FILES['image'] ['tmp_name'];
if (!isset($file)) {
echo "<br>Please select an image.";
}
else {
$image = addslashes(file_get_contents($_FILES['image'] ['tmp_name']));
$imageName = addslashes($_FILES['image']['name']);
$imageSize = getimagesize($_FILES['image']['tmp_name']);
if ($imageSize == FALSE)
echo "<br><br>Thats not an image. <br><br>";
else{
if (!$insert = mysql_query("INSERT INTO imgup VALUES ('','$imageName','$image')"))
echo "Problem uploading the image.";
else{
$lastId = mysql_insert_id();
echo "Article uploaded.<p /> Your image:<p /> <img src=get.php?id=$lastId>";
}
}
}
?>
</body>
</html>
This is my file who turn the image blob into an image:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test" ) or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM blog WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
And at the end the image does not display and this is what i get: http://goo.gl/gi1Uuc
And if i go and check my database, the image has ben successfully uploaded...
Depending on the file use inline base64 encoding. This is done with:
echo '<img src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>';
Font: base64_encode
OR
Put the T upperCase (Type), because can giving error in IE. Try printing with the function file_get_contents.
header('Content-Type: image/jpeg');
echo readfile($image);
I wouldn't store any image in a database. You should save it as file, and store the file's name in the database. You can then configure which directory an image gets served from without worrying about the full path to the image, or storing binary data in your db (yuck).
Try changing:
$image = mysql_query("SELECT * FROM blog WHERE id=$id");
to:
$image = mysql_query("SELECT * FROM blog WHERE id = '$id'");
Escaping an image file with addslashes will probably corrupt it, the imagesize test should be sufficient
here i am trying to upload the employee profile picture to mysql and then i want to fetch those picture. now i can uploaded the image into mysql db successfully but, when i try to fetch the image that doesn't fetch properly. if you open an image in texteditor na how it will look like? the same thing i got it now.. like this... (QÕf0±Ó%"÷YúEûVÚo¾e9°R}È"!5®?•Ÿ\¯ž›ÃÕîYU0T³¼´œ\aVë%z€ÙBðŒÆnPÈ Qx•eú0´ÁPÁ”·=ó-)Oyá+×½ÄS„ÞšÅS!Y¨;,¾¤ª5HÅÓôÍó3Áº¶j/"5±•RX›ee.&{ +C˜ H CÌai,F+Ô#”?Ì8««IÐO%IW).
my question is how to fetch the image properly? and then is there any other way to do store an image to mysql db. for example save a employee profile pictures to one folder and then store that link to mysql???
index.php code:
<form enctype="multipart/form-data" action="img.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include("config.php");
$query = mysql_query("SELECT * FROM tbl_images");
while($row = mysql_fetch_array($query))
{
echo "" . $row['image'] . "";
}
?>
img.php code:
<?
include("config.php");
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link) or die(mysql_error());
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
Can you try this,
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
Your code:
while($row = mysql_fetch_array($query))
{
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
}
please check the column size where you are saving the file content. The probable reason to me that you are not able to retrieve the images could be that the data is being trimmed due to size limit of the column. Try increasing the size of the column and changing the data type also, if needed. You may try the longblob datatype.
Encapsulate the echo statement in <img> tags
<form enctype="multipart/form-data" action="img.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include("config.php");
$query = mysql_query("SELECT * FROM tbl_images");
while($row = mysql_fetch_array($query))
{
echo "<img src=". $row['image'] . "/>"; // Do like this
}
?>
You need to have it rendered in the HTML as an img tag.
You should consider storing the image in a directory on the server and storing the image name/location in the database. Then create an img tag from that.
you must store you image in a folder and rename the file unique name along with the extension.
and store filename in mysql database table. i think the given code will help you.
<?
include("config.php");
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
$ext = getExtension($filename);
$new_file = "uniquename_of_file.".$ext; // you can generate unique name by any way you want.
move_uploaded_file($_FILES['image']['tmp_name'],$DESTINATION_FOLDER."/".$new_file; // upload file to the destination folder with new name
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$new_file')";
$results = mysql_query($query, $link) or die(mysql_error()); // insert new name into the database
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
function of getting extension will be as follows
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
Hey I am facing a problem in displaying images in php. The images are being stored in a table 'images' in mysql. There is another table 'restaurant' which needs to fetch those images and display respective images according to the restid. However, it is facing a problem in fetching the images and not displaying them. Please help!
This is imageupload.php:
<?php
require 'connect.inc.php';
?>
<html>
<head>
<title>Uploading image</title>
</head>
<body>
<?php
echo "<form action='imageupload.php' method='POST' enctype='multipart/form-data'>
Upload: <input type='file' name='image'><input type='submit' value='Upload' >
</form>";
if(isset($_FILES['image']['tmp_name']))
{
$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's not an image";
else
{
$query = "INSERT INTO images VALUES ('','$image_name','$image','22')";
$result = mysqli_query($con, $query);
if(!$result)
{
echo "Problem uploading";
}
else
{
echo "Image uploaded ";
$query2 = "SELECT * FROM images WHERE restid = '22'";
$result2 = mysqli_query($con,$query2);
while($info = mysqli_fetch_array($result2))
{
header("Content-type: image/jpeg");
echo $info['image'];
}
}
}
}
else
{
"Please upload a file";
}
?>
</body></html>
This is getimage.php (It fetches the image and displays it):
<?php
require 'connect.inc.php';
$id = $_REQUEST['id'];
$image = "SELECT * FROM images WHERE imgid = $id" ;
$image = mysqli_query($con, $image);
$image = mysqli_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
connect.inc.php is a file to connect to the database. I referred to other links but did not get any solid help. Please provide help.
Storing image in mysql should work.
Check that you don`t have any syntax errors.
Temporary remove Content-type header to see that image file gets printed (as gibberish string). Also check that mysql field you store image is BLOB type.
Post if you have any error there.