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.
Related
I am trying to insert a title, description and an image into an sql database, below is the form.
However, the code breaks after the form is submitted. I get redirected to the next page but none of the code in the next file gets processed.
It worked fine before I added the function to add an image and there was just text.
here is the code for the form that does not get processed correctly:
<?php
if (isset($_SESSION['username'])) {
echo "<form action='/origo/addnewtopic.php?cid=".$_GET['cid']."&scid=".$_GET['scid']."'
method='POST' enctype='multipart/form-data'>
<p>Titel: </p>
<input type='text' id='topic' name='topic' size='100' />
<p>Innehåll: </p>
<textarea id='content' name='content'></textarea><br />
<input type='file' name='image'>
<input type='submit' value='Lägg till' name='submit'/></form>"; ?>
And if anyone wonders, this is the file that it sends the info to that is trying to insert text and image to the database, but none of this gets processed.
<?php
session_start();
include ('dbconn.php');
$topic = addslashes($_POST['topic']);
$content = nl2br(addslashes($_POST['content']));
$image = ($_FILES['image']);
$cid = $_GET['cid'];
$scid = $_GET['scid'];
$insert = mysqli_query($con, "INSERT INTO topics (`category_id`, `subcategory_id`, `author`, `title`, `content`, `date_posted`)
VALUES ('".$cid."', '".$scid."', '".$_SESSION['username']."', '".$topic."', '".$content."', NOW());");
$tid = mysql_insert_id();
die($tid);
if($image) {
$insert2 = mysqli_query($con, "INSERT INTO images (`category_id`, `subcategory_id`, `topic_id`, `image`)
VALUES ('".$cid."', '".$scid."', '".$tid."', '".$image."');
}
else {
die("no image");
}
if ($insert) {
header("Location: /origo/topics.php?cid=".$cid."&scid=".$scid."");
} else {
die("error");
}
?>
try using blob datatype in the DB.
also here
$content = nl2br(addslashes($_POST['content']));
You must use $_FILES rather than $_POST. As the files like images are being stored in an array $_FILES that is later being extracted from. Also you must use file_get_contents for :
$content = nl2br(addslashes(file_get_contents($_POST['content'])));
Hope this helps a little
I have tried to insert image from database using php PDO. i have not save image directly i have store image path in my database. i am store in image path in my database.
<?php
//This is a database connection
$conn = new PDO("mysql:host=localhost; dbname=newdb;", 'root', '');
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- This is a post type form it is a upload images -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="img" required /><br><br>
<button type="submit" name="submit-img">Store Image</button>
</form>
</body>
<html/>
<?php
if (isset($_POST['submit-img']))
{
$type = ['image/jpg', 'image/png', 'image/jpeg']; //Image type name
$img = $_FILES['img']; //Fetch files
if (in_array($img['type'], $type)) //Check file type is image or not
{
$file_tmp_name = $_FILES['img']['tmp_name'];
$file_name = $_FILES['img']['name'];
$folder = "images/".$file_name;
echo $folder;
if (move_uploaded_file($file_tmp_name, $folder)) //Upload image in folder
{
$sql = "INSERT INTO images (img) VALUES (?)";
$insert_img = $conn->prepare($sql);
if ($insert_img->execute([$file_name])) //This is a image path store in database
{
echo "<script>alert('image upload successfully...')</script>";
}
else
{
echo "Image cannot uploaded please try again";
}
}
else
{
echo "file cannot uploaded";
}
}
else
{
echo "<br>Please upload an image";
}
}
?>
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>
Im currently in the process of creating a simple PHP website which can display a list of NBA teams and the respective players. One of the things I'm currently working on right now is adding the ability to upload images from the page itself instead of going to PHPMyAdmin.
Here's what the page looks like right now:
I'm trying to figure out how to add the team logo the same way I can add a new team name. As you can see in the bottom part there is an Add Team option which allows the user to add a new team and that team will be registered in the database.
I've tried to write some PHP code which enables the process of uploading images but have failed to do so.
team_list.php
<?php
error_reporting(0);
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image'];
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO categories (img) VALUES ('$image')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM categories");
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<form method="POST" action="team_list.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
And this is the add_team.php file, which gets the data from database
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
This is how the standing.php page looks like
updated add_team.php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
// This is the directory where images will be saved
$target = "../images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("renwid", "password") or die(mysql_error()) ;
mysql_select_db("nba") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO categories (img, team_name)
VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have to first upload successfully to the folder then you can add record in to your database
<?php
if(isset($_POST['submit'])) {
// This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
// mysql_connect("localhost", "root", "") or die(mysql_error()) ;
// mysql_select_db("your_db") or die(mysql_error()) ;
//Writes the information to the database
// mysql_query("INSERT INTO picture (image, team_name)
// VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Your HTML should be
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="text" name="team_name" id="team_name">
<input type="submit" value="Submit" name="submit">
</form>
Refer https://github.com/aslamanver/nbaTest
You should create a uniqid when uploading the image, this way depending on how many people will upload images, if one were to upload the same image as another, it wouldn't be overwritten in the database
You can do this by using the explode and end function in PHP, also look into prepared statements when using SQL statements, this is to protect your DB against SQL injections, here's a good link:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
The $_FILES has a few attributes including $_FILES["name"]["error"] which checks for errors, ideally you would make an if statement in which you specify the error condition for the file to uploaded to your DB. Also remember that you must first specify the directory before inserting it into your DB and if the file containing the code is in another folder, you use ../ to go back a directory.
When you display the image on your site you use this:
<img src="directory/<?php echo $row["row"]; ?>">
Can someone please help as I am at a loss. How can I get an image from MYSQL database onto my webpage. anyname.html
Database name is: upload
Table name is: images
id Primary int(11) AUTO_INCREMENT
name varchar(100)
size int(11)
type varchar(20)
content mediumblob
The upload works great but just cant get it to show the image of be able to use it in a html page. When I upload the image I get as a return: for number 11 image stored but I don't see an image: Here is my code, so please, please someone help as I have been at this for ages with no result.
my upload.php code:
<?php
// Check for post data.
if ($_POST && !empty($_FILES)) {
$formOk = true;
//Assign Variables
$path = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
$formOk = false;
echo "Error: Error in uploading file. Please try again.";
}
//check file extension
if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg', 'image/gif'))) {
$formOk = false;
echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
}
// check for file size.
if ($formOk && filesize($path) > 500000) {
$formOk = false;
echo "Error: File size must be less than 500 KB.";
}
if ($formOk) {
// read file contents
$content = file_get_contents($path);
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'root', '', 'upload')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "insert into images (name, size, type, content) values ('{$name}', '{$size}', '{$type}', '{$content}')";
if (mysqli_query($conn, $sql)) {
$uploadOk = true;
$imageId = mysqli_insert_id($conn);
} else {
echo "Error: Could not save the data to mysql database. Please try again.";
}
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
}
}
?>
<html>
<head>
<title>Upload image to mysql database.</title>
<style type="text/css">
img{
margin: .2em;
border: 1px solid #555;
padding: .2em;
vertical-align: top;
}
</style>
</head>
<body>
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Your Image has been Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="300px" height="300px"></img>
<strong><br /><br />Embed</strong>: <input size="30" value='<img src="image.php?id=<?=$imageId ?>">'>
</div>
<hr>
<?php endif; ?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>IMAGE SELECT<br /></label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<br /><br />
<input name="submit" type="submit" value="Upload Image">
</div>
</form>
</body>
</html>
It seems to be a duplicate from the issue there PHP display image BLOB from MySQL
Hope it helps.
If you store the image data in database, use the next image.php:
<?php
$id = $_GET['id'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('upload');
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>
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));