Broken Image when uploading it to MySQL Database - php

I am trying to store images into a path and then upload them into my database. The DB is called "store" and the table I'm using is called "images" containing 3 fields: id, name (varchar), image (longblob). The form is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload an Image</title>
</head>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="262144000" />
<p>File:</p>
<input type="file" name="image" accept="image/jpeg" accept="image/jpg" accept="image/png" accept="image/gif">
<input type="submit" value="Upload" name="submit" />
</form>
</body>
</html>
The upload_file.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file)){
echo "<p>Please select an image.</p>";
} else {
//$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "<p>Sorry, this is not an image.</p>";
} else {
echo "<p>File is an image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')")){
echo "<p>Problem uploading image:".mysql_error()."</p>";
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
error_reporting(-1);
?>
And get.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
$id = $_REQUEST['id'];
$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_array($image);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
?>
The images are uploaded, but are not shown. Instead, I get a broken image icon, and I don't understand why. Can someone help me??

Try to solve this problem step by step
This process can be identified as three parts and split up quickly. The HTML form, the PHP upload and saving to database process, and the loading from database process.
Try echoing the image data before inserting it into the database to see if the data is actually correct.
Update the database and see if the data is inserted there.
Load the image data from the database and echo it to see if it loads it correctly.
Try the full script.
This is just an example checklist. But you can change this and add more steps to it.
Also, please consider updating to MySQLi. You are using deprecated functions which could lead to security issues. Many information sources regarding this subject can be found on the web.

Correct the get.php code with this code
<?php
//Connect to database
$conn = mysql_connect("localhost", "tester", "");
if (!$conn) {
die("Could not connect to MySQL");
}
if (!mysql_select_db("tester")) {
die("Could not open database:" . mysql_error());
}
$id = $_REQUEST['id'];
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
You have to change the database name and user whit your own
These are the parts that i have changed:
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
echo base64_decode($image);

Related

How do i insert a image in a database and be able to show it again? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to insert a image in a database and then show it again.
At the moment it doesn't work.
So my question is how to insert a image and then show it on the page.
Tried insert and select but it doesnt work
If you want upload and show files with php try it:
1) First you will upload your file to a folder. This tutorial may be help you for upload file with PHP.
2) Create a table named like "uploaded_files" on your database and create fields under the table like "id, file_url".
3) Save $target_file value to file_url field during upload process and get it from db.
But if you want use blob for keep files in your database this tutorial may be can help you.
Try it on php:
CREATE TABLE `uploaded_files` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Connect your database named as 'db_conenct.php':
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "user";
$dbPassword = "pass";
$dbName = "your_database_name";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Create upload form with HTML, you will send your data to upload.php with "POST" method:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
upload.php
<?php
// Include the database configuration file
include 'db_connect.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $db->query("INSERT into uploaded_files (file_url) VALUES ('".$fileName."'");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
// Display status message
echo $statusMsg;
?>
Show uploaded images:
<?php
// Include the database configuration file
include 'db_connect.php';
// Get images from the database
$query = $db->query("SELECT * FROM uploaded_files ORDER BY id DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageURL = 'uploads/'.$row["file_url"];
?>
<img src="<?php echo $imageURL; ?>" alt="" />
<?php }
}else{ ?>
<p>No image(s) found...</p>
<?php } ?>
I don't know If I understand your question well but anyway I try answer it.
In my opinion there are two ways how to do it:
Upload your image to any cloud storing images or to your project structure and save in database only path of image.
Get file content and then save it to your database, eg.
$file = fopen($MY_FILE, 'r');
$file_contents = fread($file, filesize($MY_FILE));
fclose($file);
/* escape some stcharacters in file_contents before query.*/
$file_contents = addslashes($file_contents);
// Add the file in the database
mysql_connect('localhost', 'root', '') or die("Unable to connect to database.");
mysql_select_db('test') or die("Unable to select the DB.");
mysql_query("INSERT INTO files SET file_data='$file_contents'") or die("MySQL Query Error: " . mysql_error() . "
". "The SQL was: $SQL
");
mysql_close();
echo "File INSERTED into files table successfully.";
To store file binary content in database, column must be one of these types:
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB

Cannot upload image into mysql database use php

I am trying to upload a image to MySQL databases using php5 script. And I am receiving an notice error.
Error, query failed
UploadImage.php
<?php
session_start();
?>
<HTML>
<HEAD>
<TITLE> Image Upload</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" METHOD="POST" ACTION="uploadImage2.php" ENCTYPE="multipart/form-data">
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type="file" name="imgfile"/></td></tr>
<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>
UploadImage2.php
<?php
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
mysql_query($query) or die('Error, query failed'.mysql_errno($dbconn) . ": " . mysql_error($dbconn) . "\n");
$imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
//mysql_close($dbconn);
echo "<br>Image successfully uploaded to database<br>";
echo "View Image";
}else die("You have not selected any image");
?>
I have upload an image file but still have error on it.
But now I have counter another error for view Image.
<?php
// get the file with the id from database
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['id']))
{
$id = $_REQUEST ['id'];
$query = "SELECT img_name, img_type, img_size, img_data FROM img_tbl WHERE id = ‘$id’";
$result = mysql_query($query) or die(mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
print $content;
mysql_close($dbconn);
}
?>
The error code:
Notice: Undefined variable: id� in C:\xampp\htdocs\sandbox\Testing\uploadImage2_viewimage.php on line 12
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�' at line 1
Please advise...
Remove the ' ' from table fields in query .use this query :
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
also please start to use PDO or mysqli as your query is open for sql injection
This should work:
$query = "
INSERT INTO `img_tbl`
(`img_name`, `img_type`, `img_size`, `img_data` )
VALUES
('".$fileName."', '".$fileType."', '".$fileSize."', '".$imgContent."')
";
Seems that some special characters in $imgContent is breaking the query string
Please use mysql_real_escape_string to format your data before sending to the database
mysql_real_escape_string
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
UPDATE
If the first solution didn't fix the problem , please check are there any NULL values , you have some database columns which set to NOT NULL . so you cannot insert NULL values to them .
Hope this helps :)

How to display an BLOB image stored in MySql database?

I am trying to display the last 5 images uploaded to my "store" table in MySql.
I'm a complete noob to PHP and databases and i've been reading a lot on how to do this but no luck.
I can store and display pictures one at a time but i'd like to be able to have a gallery of sorts to show the last 5 uploaded.
any advice or help would be greatly appreciated thanks!
p.s. I know it frowned upon to store pictures to a database like this but this project is just for practice.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Project One</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>
<p />
<?php
//connect to database
(connect to server)
(select correct DB)
//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 = $_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 store 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>";
}
}
}
?>
<p />
<p />
Go to Gallery
</body>
</html>
get.php
<?php
//connect to database
(connect to server)
(select correct DB)
$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;
?>
This is what I used when I wanted to do something like that... a long time ago! =P
$sql = "SELECT image FROM table WHERE cond ORDER BY xxxx DESC LIMIT 5";
$result = mysqli_query($db,$sql);
while($arraySomething = mysqli_fetch_array($result))
{
echo "<img src='php/imgView.php?imgId=".$arraySomething."' />";
}
I try the first approach with header('content-type: image/jpeg'); but end up with image not shown. After a few google through website I found the solution which I can display image from database to my page
try this:
mysql_connect("localhost","root","")or die("Cannot connect to database"); //keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56"; // manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/>'
mysql_connect("localhost","root","")or die("Cannot connect to database");
//keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56";
// manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/> width="xxxx" height="xxxx"';
Add the height and width also
You can also use this function
//Retrieve image from database and display it on html webpage
function displayImageFromDatabase(){
//use global keyword to declare conn inside a function
global $conn;
$sqlselectimageFromDb = "SELECT * FROM `imageuploadphpmysqlblob` ";
$dataFromDb = mysqli_query($conn, $sqlselectimageFromDb);
while ($row = mysqli_fetch_assoc($dataFromDb)) {
echo '<img height="250px" width="250px" src=data:image;base64,'.$row['image'].'/>';
}
Insert it into mysql database like this :
$image = $_FILES['imagefile']['tmp_name'];
$name = $_FILES['imagefile']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
references : https://mauricemutetingundi.blogspot.com/2019/04/how-to-upload-blob-image-to-mysql.html

How to include variables from one page in another when writing a file with fwrite()?

Here's the code:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$tpl = file_get_contents($tpl_path.$tpl_file);
$php_file_name = $name.".php";
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl);
fclose($fp);
?>
When a user submits a picture, it is supposed to automatically create a page based on a template. Here's the code for the template:
<html>
<title><?php echo $name; ?></title>
<head>
</head>
<body>
<h1><?php echo $name ?></h1>
Posted by: <?php echo $username ?>
<br/>
<img src="<?php echo $filename ?>"/>
</body>
</html>
As you might have already guessed, I want it to put in values for name, username, and filename that were derived in the first script where they submit the picture. However, it seems they don't carry over. The page is created, but where ever it's supposed to echo the values for the variables, it is blank. How can I include the values for those variables that I want to use in the created page?
Thanks in advance to whoever can help me.
I would suggest using a string like %name%, %username% etc. to mark placeholders for variables.
Then, before writing to the file, try something like this:
$tpl = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
This will find, for example, %filename% and replace it with the contents of the variable $filename.
Look up PHP Sessions
It is a built-in feature to PHP used for exactly what you're doing.
Sessions store data on a per-user basis however, so if you're wanting other people to see the variables, you're going to have to use either a database or saving to a file.

Image upload in a database directory

i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line
upload.php
<?php
include("connecton.php");
$_SESSION['username']="kyle";
$username = $_SESSION['username'];
if($_POST['submit'])
{
//get file attribute
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if($name)
{
//start upload process
$location = "avatars/$name";
move_uploaded_file($tmp_name,$location);
$query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");
die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
}
else
die("Please select a file");
}
echo "Welcome, ".$username."!<p>";
echo "Upload Your Image:
<form action='upload.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>
</form>
";
?>
view.php
<?php
include("connecton.php");
$username = $_SESSION['username'];
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($query)==0)
die ("User not found");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
echo "<img src='$location' width='100' height='100'>";
}
?>
a) You do not check if the upload succeeded. At least do something like:
if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
... upload went ok
}
b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.
c) You do not check of the move_uploaded_file() succeeded:
if (!move_uploaded_file(...)) {
die("Move failed!")
}
d) You do not check if the database query succeeded:
$stmt = mysql_query(...)
if ($stmt === FALSE) {
die("MySQL query failed: " . mysql_error());
}
e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.
f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.
First php statement of both of upload.php and view.php should be this:
session_start();

Categories