PHP: Image is not displaying from SQL datdabase - php

I have checked out other questions of same topic on this site and tried to find the solution but unsuccessful. Images are stored in database and loaded in folder successfully but are not displayed
Here is my code:
<html>
<body>
<form action="image.php" method="post" enctype="multipart/form-data">
<input type="text" name="image_description" placeholder="Enter name" required>
<input type="file" name="myfile">
<input type="submit" name="upload" value="upload">
</form>
</body>
</html>
<?php
include("db.php");
if(isset($_POST['upload'])) {
$image_description = $_POST['image_description'];
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
$upload=move_uploaded_file($temp, "uploaded/" . $name);
$query= "INSERT INTO image(image_description,image_name,image_type,image_size) VALUES ('$image_description','$name','$type','$size')";
if(mysqli_query($conn,$query) && $upload) {
echo "successfully uploaded";
}
else
die(mysqli_error($conn));
}
$query = mysqli_query($conn,"SELECT * FROM image");
while($row = mysqli_fetch_array($query))
{?>
<img style="width: 200px;height: 200px;" src="<?php echo 'uploaded/' .$row['image_name'] ?>">
<?php
echo $row['image_description'] . "<br>";
}?>
Images are displayed as in picture
This is database table

The URL of your page is index.php/; notice the trailing slash.
A relative URL (e.g. src="uploaded/..") will resolve to index.php/uploaded/...
That folder obviously does not exist on your disk.
Use root-relative URLs: src="/uploaded/.."
or use relative URLs but go to the right folder: src="../uploaded/.."
or fix your weird URL and make it index.php, from which even relative URLs will resolve correctly.

Related

how can I upload a pdf and an image in php mysql

I am trying to upload a pdf file and an image in php mysql but it seems that the move_uploaded_file function can only work with one file. I have tried to make it work with both files but it doesn't seem to me working. It moves just the images to the target folder and adds both image name and pdf name to the database but it doesn't move the pdf to target folder. This is the code. pls help
<?php
session_start();
require_once("includedfunctions.php");
include 'dbh.php';
if (isset($_POST['submit'])){
$title=$_POST['title'];
$author=$_POST['author'];
$target = "img/pic_book/";
$target2 = "img/pdf/";
$imgname = basename($_FILES["cphoto"]["name"]);
$bookname = basename($_FILES["book"]["name"]);
$newname = $target.basename($_FILES["cphoto"]["name"]);
$newname2 = $target2.basename($_FILES["book"]["name"]);
$img_type = pathinfo($newname,PATHINFO_EXTENSION);
$book_type = pathinfo($newname2,PATHINFO_EXTENSION);
if($img_type!='jpg' && $img_type!='JPG' && $img_type!='png' && $img_type!='PNG'){
$message="Please ensure you are entering an image";
}else{
if($book_type != 'pdf'){
$message="books must be uploaded in pdf format";
}else{
if(!preg_match("/^[a-zA-Z'-]+$/",$author)){
$message = "<p style='color:red'>Please enter the real name of the author; not a nickname.</p>";
}else{
if (move_uploaded_file($_FILES["cphoto"]["tmp_name"], $newname)) {
if(move_uploaded_file($_FILES["book"]["tmp_name"], $newname2));{
$sql = "INSERT INTO books (Title, Author, pathtopdf, pathtoimage) VALUES ('$title', '$author', '$bookname', '$imgname')";
$result = mysqli_query($conn, $sql);
if($result){
$message = "upload successful";
}else{
$message = "upload failed1";
}
}
}else{
$message = "upload failed";
}
}
}
}
}
else{
$message="";
$title="";
}
?>
<html>
<head>
<title>Libraria</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/contactcss.css" rel="stylesheet">
<script src="js/respond.js"></script>
</head>
<body>
<br><br><br><br><br>
<!-- content -->
<div class="container">
<?php
echo '<p>Welcome ' . $_SESSION['name']. '</p><br>';
echo '<p>' . $message. ' </p>';
?>
<br><br>
<!--form-->
<div class="row">
<form action="admin2.php" method = "post" enctype="multipart/form-data">
<label for="Title">Title</label><br>
<input type="text" id="fname" value ="<?php echo $title; ?>" name="title" placeholder="Title of the book" required><br>
<label for="author">Author</label><br>
<input type="text" id="lname" name="author" placeholder="Author of the book" required><br>
<label for="Cover photo">Cover photo</label><br>
<input type="file" id="cphoto" name="cphoto" required><br>
<label for="book">Book</label>
<input type="file" id="book" name="book" required><br>
<button class="submit" type="submit" name="submit"><b>Upload</b></button>
</form>
</div>
</div>
</body>
</html>
Code is all correct. just check pdf size. if size is more than 4MB than it will not allowed to upload. you need to increase upload file size in php.ini file or apache config settting file.
Have a great day :)
application/pdf is the mime type for pdf not just pdf.

How to solve broken image displayed using php after upload to database

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>

How to Display image Using Session in PHP

i am able to display image on screen but i want to display the image using session.Please help me.
$_SESSION['user_name6'] = $_FILES["file"]["name"];
if(isset($_SESSION['user_name6']))
{
echo "<img src=<?php echo $_SESSION[user_name6]; ?> width=300 height=400
alt=Image path Invalid name=image />";
}
else
{
print "no pic here";
}
I do not know what you will actually do but this is the approach that best fits
when you put a file type in your form, you need to use the global variable Files
form.html
<form action="process.php" method="post" enctype="multipart/form-data">
<label for="picture">Picture:</label>
<input type="file" name="picture" id="picture"><br>
<input type="submit" name="submit" value="Upload">
</form>
process.php
<?php
session_start();
//make sure you have created the **upload** directory
$filename = $_FILES["picture"]["tmp_name"];
$destination = "upload/" . $_FILES["picture"]["name"];
move_uploaded_file($filename, $destination); //save uploaded picture in your directory
$_SESSION['user_name6'] = $destination;
header('Location: display_picture.php');
display_picture.php
<?php
session_start();
?>
<div>
<img src="<?php echo $_SESSION['user_name6']; ?>" alt="picture"/>
</div>

How to display all the images stored inside a database

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;

myproblem in uploading in php

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.

Categories