Displaying images from mysql database - php - php

I am currently having problems with displaying image from mysql database. I am able to upload an image to mysql database, however if i want to retrieve it from the database, it is displayed in Gibberish text.
Here is upload.php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$filename = mysqli_real_escape_string($mysqli,$_FILES['image']['name']);
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO `TABLES` (`image`)
VALUES( NULL,'$data')";
$result = $mysqli->query($query);
}
View.php
$mysqlquery = "SELECT * FROM TABLE";
$results = $mysqli->query($mysqlquery);
if($results->num_rows > 0){
while ($row = $results ->fetch_assoc()){
echo '<div align = "center">';
echo "<b>".$row["image"]. "<br></b>";
header("Content-type: image/jpeg");
}
}

Try this and do not forget to give image path before source
echo "<img src='your image location directory/". $row['image'] .'" >";

Oooooh... I just wish I had the answer to this one...
Some thoughts, though.
First, from personal experience I urge against storing images in the database. For one thing, your database backups will quickly become ridiculous. A more common, and better, approach is to store the images in the file system and store only the location (e.g. /img/pic03.jpg ) of the image in the database.
Next, I see you are modifying the received binary data:
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
Perhaps you know something that I don't (it's not difficult), but generally, if you gerfingerpoke with binary image data you get ... um... gibberish. Try disabling those lines and see what happens.

Related

PHP image compression and uploading to mysql

I have a php script, which uploads pictures to a mysql database. The images are taken within the browser. I would like to compress them before uploading, but I'm not quite sure how exactly to compress the uploaded data. What I've got for the moment is this:
if(isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0)
{
//$positiony = $_POST['posy'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$content = imagejpeg($content,null,50);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (team_name, id, display, content) ".
"VALUES ('$team_name', 'null', '1', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
echo "<br>File $fileName uploaded<br>";
}
The image uploading works fine, but the uploaded images are broken. Introducing imagejpeg as a form of compressing has caused the issues. Should I be using it on something else?
Most images are already compressed so there is no need to "compress them further".
Storing them in a database is not a recommended thing to do. Just upload them to a location on the server and save the path to that location.

Getting Errors When Downloading Files From SQL Database

I am running a website, and part of the site is allowing users to upload files to a SQL database, and then download them. The download itself works, but the file is getting corrupted. Image files cannot be opened, doc files are showing up as blank. I will attach below my uploading script and my downloading script.
$classid = $_POST['uploadclass'];
$userid = $_SESSION['id'];
$view = $_POST['view'];
$filename = $_FILES['uploadfile']['name'];
$tmpname = $_FILES['uploadfile']['tmpname'];
$filesize = $_FILES['uploadfile']['size'];
$filetype = $_FILES['uploadfile']['type'];
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);
if (!get_magic_quotes_gpc()){
$filename = addslashes($filename);
}
$query = "INSERT INTO uploads VALUES('','$filename', '$filetype', '$filesize', '$content', '$userid', '$classid', '$view', 'no')";
$run = mysqli_query($connect, $query);
mysqli_close($connect);
header('location: files.php');
Below is the code for my download page.
$query = "SELECT * FROM uploads WHERE id=$id";
$run = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($run)){
$name = $row['name'];
$type = $row['type'];
$size = $row['size'];
$content = $row['content'];
}
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
You are incorrectly handling the files and everything else when inserting them into the database. All files that are already there are damaged and probably destroyed.
addslashes() is no escaping function for a database. Always use the escaping function that comes with the DB extension you are using. If you are using mysqli, then the correct function must be mysqli_real_escape_string().
You should however have a look at prepared statements. These will use an different way of transferring the data that does not need escaping. Do pay attention however to the setting of magic quotes. The preferred setting is OFF, and the recent PHP versions starting with 5.4 have this feature removed already. So you have to deal with escaping the data you insert into the database anyway.

php mysql upload an image to database

Found several examples online on how to upload an image to a mysql database table, in binary
NOT a link or a folder in the server.
the imag isn't viewable when i try to print it
when I check the database table,it shows a bunch of data in weird format, i'm assuming the image data
here is code
if(!empty($_FILES['image']) && $_FILES['image']['size'] > 0 && !empty($_POST['name']))
{
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
code for displaying image
$sql = "SELECT * FROM `photos` WHERE userName = '$currentUser'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$content = $row['image'];
echo $content;
echo '<p id="caption">'.$row['caption'].' </p>';
}
when i try to display the image i get nothing as output, i check the database via putty, and i see a massive amount of weird characters, i'm assuming the items for the image.
ideas?
you could eventually try to replace these two lines:
$content = $row['image'];
echo $content;
with:
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';

How to upload and display images in mysql

I would like to ask you how can I properly stored an image both in mysql and in a folder at the moment with this code:
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$data')";
$results = mysql_query($query, $conn);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
?>'
Also how properly to display it.
My database for the images is id, images. Do I need anything more for the job or that is enough.
Thank you.
From the above code, image will be saved in database not in folder.
To save in folder you have to use a below code after insert query.
move_uploaded_file($tmpName,"upload/" .$filename );
here upload is folder name.
If you want to store image in database you can use base64_encode method
$image = file_get_contents('filename.gif');
$imencoded = base64_encode($image);
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$imencoded')";
But storing image in db is not recommended and it will not support in IE6 & 7.

How to resize an image file on php?

I have an image file which is stored onto database as a blob (shown in the code). Once resized to 80*80(thumbnail) I need to store it onto some other database. I have resized and saved it as a file but I couldn't store the resized image onto database. How can I achieve this?
//resize image and save
include('MyImage.php');
$image = new MyImage();
$image->load($tmpName);
$image->resize(80,80);
$image->save('thumbnail.jpg');
//storing original image onto database
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO image_tbl (name, size, type, content )".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
}
The direct question to your answer is
//This goes after the frist block, after "$image->save('thumbnail.jpg');"
$fileSize=filesize('thumbnail.jpg')
$fp = fopen('thumbnail.jpg', 'rb');
$content = fread($fp, $fileSize);
$content = addslashes($content);
fclose($fp);
$query = "INSERT INTO image_tbl (name, size, type, content )".
"VALUES ('thumbnail.jpg', '$fileSize', 'image/jpeg', '$content')";
mysql_query($query) or die('Error, query failed');
You might recognize some elements of that code :-)
But believe me, you do not want this:
Storing BLOBs in the DB, that the DB doesn't understand is a bad idea
using strings and addslashes to achieve it, is very close to the worst case possible: You read the image into a string consisting of ca 50% unprintables, backslash it, transport it to the DB, where it is unbackslashed and parsed. Use prepared statements with parameters (if you really want to save the image in the DB)
Try this:
$file = $path_you_saved_image."/".$your_image_name;
$handle = fopen( $file , "rb" );
$img = fread($handle , filesize($file) );
$img = base64_encode($img);
$query = "insert into images (image) values ('$img')";
mysql_query($query) or die(mysql_error());
you code suggests that you have saved the resized image. Now open this resized image 'thumbnail.jpg' and process it, encode it and save it.

Categories