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.
Related
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
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!";
I need a help to upload and show an image from a database in PHP, I created a database that name is students contains the ID, image size,and image name, is there is a way to do that?
I searched on youtube about this but I found this code, but this code save to a directory.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
So, is there any way to save an image to a database and view it from a database?
You can save it into a MySQL table as a Blob but this isn't a really a good idea. Explanation here: http://www.hockinson.com/programmer-web-designer-denver-co-usa.php?s=47
Do what FDl said in the comments. Give each image a unique name and save it to your server, then save its unique name into your database.
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.
having a big trouble trying to make this blob saved to a file and load it as an image.
Using SQLite Manager (Firefox Add-on) I was able to "Save As" a file with the content of my image BLOB. The result is a strange (for me) code.
Since I can´t post the "source of the file", I'm attaching one png with the example.
In my Mac, the saved file has no extention but I can view the image it produces as thumbnail.
So I'm trying to achieve the same result saving one file, but all I get is a 16 bytes document I can't read...
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'w');
fwrite($pic, base64_encode($theFile));
fclose($pic);
* EDIT *
$theFile = shell_exec("sqlite3 AddressBookImages.sqlitedb 'select data from ABThumbnailImage where record_id = ".$id."'");
if($theFile != '') {
file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $theFile);
}
Try to use (b for binary)
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'wb');
I find a solution to this, but its very slow, I'm posting a new question to ask help for improve this.
$sql2 = shell_exec("sqlite3 ".$endereco_iphone."".$db_pics." 'select hex(data) from ABThumbnailImage where record_id = ".$id."'");
//
if($sql2 !='' && $sql2 != 'NULL') {
$img = '';
foreach(explode("\n",trim(chunk_split($sql2,2))) as $h) {
$img .= chr(hexdec($h));
}
if(file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $img)) {
$cnt .= "<img class='pics' src='pics/thumbnails/pic_".$id.".jpg' width='30px' height='30px'></img>";
}
} else {
$cnt .= "<div class='pics'></div>";
}