Image can't display from database in php and it's fire such error.
When I execute this code such error is occure The image cannot be display beacuse it's contain error. Image is store in mysql database and field type is BLOB. IT didn't find any solution to avoid this error.
<?php
require_once('database/db.class.php');
$objDatabase=new db_class();
$objDatabase->connect();
$sql="SELECT id,firstname,lastname,sex,email,userimage,ext,city,state,username FROM t_users WHERE username='".$_SESSION['username']."'";
$totalRow=$objDatabase->select($sql);
if($row=$objDatabase->get_row($totalRow, 'MYSQL_BOTH'))
{
$userArray=array('id'=>$row['id'],'firstname'=>$row['firstname'],'lastname'=>$row['lastname'],'sex'=>$row['sex'],'email'=>$row['email'],'userimage'=>$row['userimage'],'ext'=>$row['ext'],'city'=>$row['city'],'state'=>$row['state'],'username'=>$row['username']);
}
?>
<table cellspacing="10px" width="100%">
<tr>
<td width="23%" style="vertical-align:top">
<?php
header("Content-type: image/{$userArray['ext']}");
header("Content-Length: " . strlen($userArray['userimage']));
echo $userArray['userimage'];
?>
</td>
</tr>
</table>
Upload Image Code
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
$img = file_get_contents($_FILES['photo']['tmp_name']);
$img = mysql_real_escape_string($img);
// Preparing data to be used in MySQL query
$data=array('firstname'=>$_REQUEST['firstname'],'lastname'=>$_REQUEST['lastname'],'sex'=>$_REQUEST['gender'],'email'=>$_REQUEST['email'],'userimage'=>$img,'ext'=>$ext,'city'=>$_REQUEST['city'],'state'=>$_REQUEST['state'],'zipcode'=>$_REQUEST['zipcode'],'username'=>$_REQUEST['usernameText'],'password'=>$_REQUEST['passwordText']);
$result=$objDatabase->insert_array('t_users',$data);
<input name="photo" type="file" id="photo">
edit - I forgot to include: base64 files will be considerably larger than BLOB.
Try saving it as base64 instead of BLOB.
Here is a function I found on http://www.php.net/manual/en/function.base64-encode.php
function base64_encode_image ($filename=string,$filetype=string) {
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
When you retrieve the image from the database, it will be as a base64 string, you can put the string directly into the src="" attribute in your HTML (no need to decode). Browsers can parse base64 and display an image.
Well, this isn't the way to do it, just store the image as per usual, then store the path in the database.
If you do want to do it this way, you'll need to make a new file, called something like image.php, then put
<?php
require_once('database/db.class.php');
$objDatabase=new db_class();
$objDatabase->connect();
$sql="SELECT id,firstname,lastname,sex,email,userimage,ext,city,state,username FROM t_users WHERE username='".$_SESSION['username']."'";
$totalRow=$objDatabase->select($sql);
if($row=$objDatabase->get_row($totalRow, 'MYSQL_BOTH'))
{
$userArray=array('id'=>$row['id'],'firstname'=>$row['firstname'],'lastname'=>$row['lastname'],'sex'=>$row['sex'],'email'=>$row['email'],'userimage'=>$row['userimage'],'ext'=>$row['ext'],'city'=>$row['city'],'state'=>$row['state'],'username'=>$row['username']);
}
header("Content-type: image/{$userArray['ext']}");
header("Content-Length: " . strlen($userArray['userimage']));
echo $userArray['userimage'];
?>
in to that file.
Then in the table use
<img src='/image.php ?>' alt='' />
But don't, just do it by storing the path in the DB, it's rare that you should be storing binary data in a database that's not the file system, for reasons I won't go into here.
Related
I'm trying to display an image along with other information from the database.
PHP
<?php
mysql_connect("localhost","111","222") or die("Could not connect to localhost");
mysql_select_db("movies") or die( "Could not connect to database");
$result = mysql_query("SELECT * FROM allmovies");
if ($result == false ) die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<img src=' . $row['image'] . '>";
?>
Like:
Title: Blah
Price: Blah
Image: <img src=rarara">
All from MySQL in one page?
Don't store image data in a database, they are generally not suited to this and incurs extra overhead on your MySQL connections returning the data. You should be storing the path to the image file, and serving that.
If you insist on doing it you you should only be returning one image at a time with the proper header based on the image type using something like the following:
$imagedata = data_from_mysql();
header('Content-Length: ' . sizeof($imagedata) );
header('Content-Type: image/png');
echo $imagedata;
exit;
If you really want to make your page source bloated, slow, unmanageable, and nigh-uncacheable:
while( $imagedata = data_from_mysql() ) {
echo "<img src='data:image/png;base64," . base64_encode($imagedata) . "'>";
}
I cannot stress enough how these are terrible ideas that you should not use, but if you cannot listen to reason you can at least do bad things the right way.
You could use imagecreatefromstring()
$im = imagecreatefromstring($row['image']);
if ($im !== false) {
ob_start();
imagejpeg($im);
$data = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpg;base64,' . base64_encode($data) . '" />';
}
Just my opinion, but it might be slightly more sane to save the images to the file server and then store a reference to the path instead of the whole image as a blob?
I am trying to upload things to a database. I went through a few tutorials and none of them worked. I want to upload files such as images and text documents (including PowerPoint presentations) to the database.
This is my form
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture" type="file" id="picture" size="50">
<input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>
This is upload.php
<?php
// if something was posted, start the process...
if(isset($_POST['upload']))
{
// define the posted file into variables
$name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
$type = $_FILES['picture']['type'];
$size = $_FILES['picture']['size'];
// get the width & height of the file (we don't need the other stuff)
list($width, $height, $typeb, $attr) = getimagesize($tmp_name);
// if width is over 600 px or height is over 500 px, kill it
if($width>600 || $height>500)
{
echo $name . "'s dimensions exceed the 600x500 pixel limit.";
echo 'Click here to try again.';
die();
}
// if the mime type is anything other than what we specify below, kill it
if(!($type=='image/jpeg' || $type=='image/png' || $type=='image/gif'))
{
echo $type . " is not an acceptable format.";
echo 'Click here to try again.' ;
die();
}
// if the file size is larger than 350 KB, kill it
if($size>'350000') {
echo $name . " is over 350KB. Please make it smaller.";
echo 'Click here to try again.' ;
die();
}
// if your server has magic quotes turned off, add slashes manually
if(!get_magic_quotes_gpc()){
$name = addslashes($name);
}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, $size);
$content = addslashes($content);
fclose($extract);
// connect to the database
include "inc/db.inc.php";
// the query that will add this to the database
$addfile = "INSERT INTO files (name, size, type, content ) ".
"VALUES ('$name', '$size', '$type', '$content')";
mysql_query($addfile) or die(mysql_error());
// get the last inserted ID if we're going to display this image next
$inserted_fid = mysql_insert_id();
mysql_close();
echo "Successfully uploaded your picture!";
// we still have to close the original IF statement. If there was nothing posted, kill the page.
}
else{
die("No uploaded file present");
}
?>
I know there is restriction on type -> if(!($type=='image/jpeg' || $type=='image/png' || $type=='image/gif')) on this. When I upload small photos, the error I am getting is "No database selected".
The database is configured correctly as other things that I have are able to connect to it.
Your code is fundamentally broken:
1) You simply assume an upload was performed, and never check for failure. At minimum you should have
if ($_FILES['picture']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['picture']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
2) addslashes() provides about as much defense against SQL injection attacks as using a single square of wet toiler paper does to drying up a lake. Since you're using the mysql library, you MUST use mysql_real_escape_string() to do a PROPER job of escaping the data
3) You're using the mysql library, which is obsolete and deprecated. STOP USING IT. Switch to mysqli or PDO instead.
4) Your actual error message indicates that you never did a mysql_select_db() call to set your default database. You could get around it by simply modifying your query to be INSERT INTO name_of_db.name_of_table ....
Make sure that you correctly called mysql_select_db() in your inc/db.inc.php file.
In the code below you are simply echoing the text without performing any check. The success message will be displayed irrespective of success or failure.
echo "Successfully uploaded your picture!";
Having big time problems in displaying an image out of my mysql database
I'm storing it in a longblob type
when the image is displayed i get a broken image icon
here is code for storing image
if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
//temporary file name
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$imageType = $_FILES['image']['type'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
VALUES
('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";
//For debugging purposes
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Your Image has been Added";
}
}
then printing the image
if(isset($_POST['usersImage'])){
//code to show images
$user = $_POST['usersImage'];
$sql = "SELECT * FROM `photos` WHERE userName = '$user'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
switch ($row['photoType']) {
case 'image/jpeg':
echo "<tr>";
echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";
echo "</tr>";
//echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
//echo '<p id="caption">'.$row['caption'].' </p>';
break;
}
}
}
as you can see my latest attempt was to use base64 encoding to print out the image
my previous try was the commented out code
When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.
<?php
$photo_bin = //binary data from query here;
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $photo_bin;
Quick example^ of a php script that can be requested by the browser from an img tag.
Validation is important. You are opening yourself up to so many security issues.
Never use $_POST / $_GET inside a sql statement. Escape them, better yet, use PDO statements. Validate that the image is actually an image, at this point, you could be entering any type of file into your table.
As you're finding, it's also far more difficult to store images in a database than on the filesystem. Usually, there are far more arguments to store the image on the filesystem than inside a table.
Having a quick look down your insertion code, I'm not quite sure why you're adding slashes to the binary data. remove the call to addslahes, and try that.
I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out.
This is my upload function:
function upload(){
global $imagefolder, $id;
global $tbl_units;
include "globalizePOSTGET.php";
// $uid = uuid();
$minsize = 5000; // 5kb
$maxsize = 3000000; // 3mb
$ext = explode('.',basename($_FILES['userfile']['name']));
$ext = $ext[count($ext)-1];
$ext = strtolower($ext);
if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
echo "<script> alert('Image is not a png or jpeg format'); </script>";
return false;
}
$imagename = $_POST['id']."_img".$_FILES['img'].".$ext";
$imagename2 = "X_".$imagename;
$uploadfile = $imagefolder . $imagename;
$uploadfile2 = $imagefolder . $imagename2;
$uploadthumb = $imagefolder . "tn_" . $imagename;
if (file_exists($uploadfile)) unlink($uploadfile);
if (file_exists($uploadthumb)) unlink($uploadthumb);
if (file_exists($uploadfile)) {
echo "<script> alert('Image already exists!'); </script>";
}
else
{
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// check the file is less than the maximum file size
if($_FILES['userfile']['size'] < $maxsize) {
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion
$size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info..
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) {
$Image = #imagecreatefromjpeg($uploadfile2);
if ($Image) {
$img_height = imagesy($Image);
$img_width = imagesx($Image);
imagedestroy($Image);
}
if ($img_height > $img_width) { // portrait
$tempMultiplier = 150 / $img_height;
$tempMultiplierFull = 600 / $img_height;
} else {
$tempMultiplier = 150 / $img_width;
$tempMultiplierFull = 600 / $img_width;
}
$imageHeight = $img_height * $tempMultiplier;
$imageWidth = $img_width * $tempMultiplier;
$fullimageHeight = $img_height * $tempMultiplierFull;
$fullimageWidth = $img_width * $tempMultiplierFull;
createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight);
if($_FILES['userfile']['size'] > $minsize) {
createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight);
if (file_exists($uploadfile2)) unlink($uploadfile2);
} else {
rename($uploadfile2, $uploadfile);
}
$sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
echo $sql;
if(!mysql_query($sql)) {
echo "<script> alert('Unable to upload file'); </script>";
} else {
?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php
}
}
} else {
// if the file is not less than the maximum allowed, print an error
$file_n = basename($_FILES['userfile']['name']);
$file_s = $_FILES['userfile']['size'];
?>
<script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script>
<?php
}
}
}
}
I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:UPDATE member_units SET photo = "_img.jpg" WHERE id = `
Someone please help me! I am very inexperienced in PHP and I have no idea what to do here.
Here is the form that is doing the uploading:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="hidden" name="_submit_check" value="1" />
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="img" value="<?php echo $img; ?>" />
Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;">
<input type="submit" value="Submit" onClick="return validate();">
<input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';">
</form>
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement...
UPDATE member_units SET photo = "_img.jpg" WHERE id = `
This corresponds to...
UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
We can see by comparison that it is clear that $_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $_POST['id'], while $imagename gives a short _img.jpg file name.
Tracking back you can then see that $imagename comes from...
$_POST['id']."_img".$_FILES['img'].".$ext";
This is where your photo = "_img.jpg" comes from. Again, $_FILES['img'] and $_POST['id']
The fact that you're reaching the echo statement means that something is uploading, but it is through the $_FILES['userfile'] array, with all of it's associated variables, for example $_FILES['userfile']['name'] which would give you the filename of the image being uploaded.
What you need to ask yourself next is where you are expecting $_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1_imgLolCat.jpg then your variable will need to look more like
$imagename = $_POST['id']."_img".$_FILES['userfile']['name'];
However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from...
$imagename = $_POST['id']."_img".$_POST['img'].".$ext";
...if a HTML field exists with the name "img"!
Finally take a look at your SQL statement...
SET photo".$_FILES['img']." = \"" . $imagename . "\"
And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $_POST['img'] in there.
Word of warning, you need...NEED to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take
SET photo".$_POST['img']
and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ?
Be careful, your script can be the target of an SQL injection : you use a user input ($_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.
I have a simple file uploader, which thanks to stackoverflow is now fully working, however when I copied the PHP code across to my main layout, once initialised to upload a file, but it is wrong format or size and it echos the error, it breaks the HTML below it. Im thinking its to do with the "exit;" after each echo? but could be wrong.
<?php
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
exit;
}
#we have a filename, continue
#directory to upload to
$uploads = '/home/habbonow/public_html/other/quacked/photos';
$usruploads = 'photos';
#allowed file types
$type_array = array(image_type_to_mime_type(IMAGETYPE_JPEG), image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_PNG), 'image/pjpeg');
if(!in_array($_FILES['image']['type'], $type_array))
{
#the type of the file is not in the list we want to allow
echo "<br/><b>That file type is not allowed!\n</b>";
exit;
}
$max_filesize = 512000;
$max_filesize_kb = ($max_filesize / 1024);
if($_FILES['image']['size'] > $max_filesize)
{
#file is larger than the value of $max_filesize return an error
echo "<br/><b>Your file is too large, files may be up to ".$max_filesize_kb."kb\n</b>";
exit;
}
$imagesize = getimagesize($_FILES['image']['tmp_name']);
#get width
$imagewidth = $imagesize[0];
#get height
$imageheight = $imagesize[1];
#allowed dimensions
$maxwidth = 1024;
$maxheight = 1024;
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
#one or both of the image dimensions are larger than the allowed sizes return an error
echo "<br/><b>Your file is too large, files may be up to ".$maxwidth."px x ".$maxheight."px in size\n</b>";
exit;
}
move_uploaded_file($_FILES['image']['tmp_name'], $uploads.'/'.$_FILES['image']['name']) or die ("Couldn't upload ".$_FILES['image']['name']." \n");
echo "<br/>The URL to your photo is <b>" . $usruploads . "/" . $_FILES['image']['name'] . "</b>. Please use this when defining the gallery photos";
}
?>
<form name="uploader" method="post" action="" enctype="multipart/form-data">
<input type="file" name="image" style="width:300px;cursor:pointer" />
<input type="submit" name="upload" value="Upload Image" />
</form>
Indeed, when you call exit; it means "immediately stop all processing; this script is finished." Anything that comes after it — including HTML — will not be interpreted.
A better organization would be to make this code a function, to the effect of:
function uploadMyStuffPlease() {
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
return;
}
#we have a filename, continue
// ....
}
Now you can simply call uploadMyStuffPlease(), which will do as much processing as it can, and perhaps return early in the event of an error. Either way, the function will return, and so the rest of your script (including that HTML) can still be interpreted.
If you call exit; your PHP script won't be able to output anything anymore. That's why the layout is broken.
You should maybe try to keep the HTML parts out of your PHP code and especially avoid opening tags that you don't close afterwards (i.e. divs or anything).
That being said, it's probably safest to just put everything into a function that won't exit the script when finished (see other's posts).
if(isset($_POST['upload'])){
OR
if(!empty($_POST['upload'])){
And remove exit...