PHP - Display Image From Blob Not Working
it should display the image but nothing appears. what have i done wrong?
Code: [Select] echo "<img src=\"photo.php?id=$studentid\" alt='photo' />"; photo.php Code: [Select] <?php $id= $_GET['id']; $getphoto= mysql_query("SELECT photo FROM Student WHERE SID=$id LIMIT 1"); $row5 = mysql_fetch_assoc($getphoto); $photogot = $row5['PHOTO']; header("Content-type: image/gif"); print $photogot; ?> Similar TutorialsCode: [Select] $thephoto = $row['thePHOTO']; in mysql thephoto is BLOB file type and stores an image i want to display the image as an avatar, in a while loop. Code: [Select] while($row = mysql_fetch_assoc($query4)) { $id = $row['ID']; $thename = $row['theNAME']; $thephoto = $row['thePHOTO']; } how do i make blob readable and then display as an image? Hi guys, I have a problem. I need to create a page that has a web form to upload an image to a mySQL database and place it in a blob field. Then I need to be able to query the database later to display the image on the site. I've looked around but I just haven't found any examples that can help me. Does anyone know of any good example or can anyone please give me an example? I have nothing so far, just the html web form and database. I using.. this is my 3 files which is i am using to show data of customer but i am not able to see them their logo image please see them & help me guys i dont know whats wrong in this. these files i uploaded please find attachment to see them. thnx in advanced [attachment deleted by admin] Hi everyone, i am just trying to learn php for a bit of fun really and started making a sort of 'facebook' website. I am having trouble however trying to display different users images, for example when trying to find a correct 'friend' only the image of the last result is being shown for all people with the same name... here is my code below, if anyone can help me out that would be great file 1 $count=1; while ($numids>=$count){ echo "<form method=\"post\" action=\"friendadded.php\">"; $frienduserid=$_SESSION["passedid[$ii]"]; $friendfirstname=$_SESSION["passedfirstname[$ff]"]; $friendlastname=$_SESSION["passedlastname[$ll]"]; $_SESSION['friendsuserpicid'] = $frienduserid; echo "<table width=\"700\" height=\"50\" border=\"1\" align=\"center\">"; echo "<tr>"; echo "<th></th>"; echo "<th>First Name</th>"; echo "<th>Last Name</th>"; echo "</tr>"; echo "<tr>"; echo "<td><center>"; echo "<img border=\'0\' src=\"frienduserpic.php\" width=\"80\" height=\"80\" align=\"middle\"/>"; echo "</center></td>"; echo "<td><center>"; echo $friendfirstname; echo "</center></td>"; echo "<td><center>"; echo $friendlastname; echo "</center></td>"; echo "</tr>"; echo "</table>"; echo "<center><input type=\"submit\" value=\"Add this friend\" name=\"Add Friend\"></center><br/>"; $ii=$ii+1; $ff=$ff+1; $ll=$ll+1; $count=$count+1; echo "</form>"; } file 2 session_start(); $passeduserid=$_SESSION['friendsuserpicid']; $timespost=$_SESSION['postednum']; $host= $username= $password= $db_name= $tbl_name= mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $query = mysql_query("SELECT * FROM $tbl_name WHERE picid='".$passeduserid."'"); $row = mysql_fetch_array($query); $content = $row['image']; header("Content-type: image/jpeg"); echo $content; Thanks in advance Hi! I am building a little PHP/MySQL application where pictures are uploaded and stored in MySQL in a longblob. These are special circumstances and storing images in the database in an absolute must. Uploading is working fine. The upload script inserts the following into the field `image_data`: base64_encode(file_get_contents($_FILES['image']['tmp_name'])) The problem is displaying the images. I cannot for the life of me make it work. I've tried the code on multiple systems with various versions of PHP and MySQL. I have two files: one called view.php and one called show.php. # view.php # It gets $info['id'] from a query getting the ID of the recent-most image uploaded. echo '<img src="show.php?id='.$info['id'].'" alt="" />'; # show.php # $id is determined by $_GET['id'] and passes through security checks I've omitted here. # There is zero (not even a whitespace) output before the header()s are sent. $query = "SELECT `image_data`,`image_mime`,`image_size` FROM `upload`.`files` WHERE `id` = '$id';"; $sql = mysql_query($query) or die(mysql_error()); $image = mysql_fetch_assoc($sql); header('Content-Type: ' . $image['image_mime']); header('Content-Length: ' . $image['image_size']); echo base64_decode($image['image_data']); The problem is that no image is displayed either in view.php or when I call show.php directly with a valid ID. I have verified that $image['image_mime'] and $image['image_size'] contain the right data. However, if I download show.php and change extension to for example .jpg, the image is there. So the image is stored correctly in the database and $image['image_data'] is outputting the right data. I even compared checksums for the image before and after and they're identical, so I would conclude that the error is in the outputting of the image - but I can't figure out what. Error_report is set to E_ALL but there's nothing useful coming out. Any ideas? Hi everyone, I've read lots of tutorials on this, but something is not clicking in my brain with it. I think my coding is close, but, as of right now, all I get is a red x for the image when I try to display the image. Let me share my code as a starting point - I would truly appreciate any helpful comments or blatant errors that are pointed out or shared with me. Here is the upload image form and code (so they clicked the item name and then go into this): if($_REQUEST['modifyfeatured']) { $id=$_REQUEST['modid']; $sqlid="SELECT * FROM product WHERE id='$id'"; $resultid=mysql_query($sqlid, $dbh); $idrow = mysql_fetch_array($resultid); echo "<p>"; echo "Fill out the form below to add a short text line (i.e. 20% Off!) and/or an image (like the new note).<br>"; echo "You are modifying the following item: <p><b>"; echo $idrow['product_id']; echo " "; echo $idrow['title']; echo "</b><p>"; ?> <table border="0" cellpadding="2" cellspacing="0"> <tr> <td> <form method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="<? echo $id; ?>"> Short Text Message: </td><td> <input type="Text" name="message"></td></tr> <tr><td>Small Image:</td><td> <input type="hidden" name="MAX_FILE_SIZE" value="2000000"> <input name="userfile" type="file" id="userfile"></td></tr> <tr><td> </td><td> <input name="upload" type="submit" class="box" id="upload" value="Submit"> </td></tr></table> </form> <? } //then when the click the upload link, here is the code for that: 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']; $message=$_REQUEST['message']; $id=$_REQUEST['id']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } include 'library/config.php'; include 'library/opendb.php'; //$query = "INSERT INTO featured_prods (name, size, type, image, message ) ". //"VALUES ('$fileName', '$fileSize', '$fileType', '$content', '$message')"; $query="UPDATE featured_prods SET name='$fileName', size='$fileSize', type='$fileType', image='$content', message='$message' WHERE id='$id'"; //$sqldone="UPDATE product SET product_id='$product_id', title='$title', description='$description', regular_price='$regular_price', sale_price='$sale_price', stat='$stat', weight='$weight', close_out='$close', additional='$additional', additionalpix='$additionalpix_name' WHERE id='$id'"; //$resultdone=mysql_query($sqldone, $dbh); mysql_query($query) or die('Error, query failed'); include 'library/closedb.php'; echo "<br>File $fileName uploaded<br>"; } //end if upload is hit Okay, now here is the code trying to display the image: <? $featuredquery="SELECT * FROM featured_prods"; $featuredresult=mysql_query($featuredquery, $dbh); while($featuredrow=mysql_fetch_array($featuredresult)){ $id=$featuredrow['id']; $prodquery="SELECT * FROM product WHERE id='$id'"; $prodresult=mysql_query($prodquery, $dbh); $prodrow=mysql_fetch_array($prodresult); echo $prodrow['title']; echo "<br>"; echo $featuredrow['message']; echo "<br>"; ?> <img src="getimage.php?id=<?echo $id;?>" alt="cover" /> <? } And here is the code for getimage.php: <? $id=$_GET["id"]; $result = mysql_query("select image from featured_prods where id='$id'"); $row = mysql_fetch_row($result); $data = base64_decode($row[0]); $im = imagecreatefromstring($row[0]); imagejpeg($im); header('Content-type: ' . image/jpeg); // 'image/jpeg' for JPEG images echo $data; ?> Again, any help would be appreciated. I'm a real rookie here, and I appreciate everyone's time and effort to assist me very much. Code: [Select] echo '<img src="data:image/jpg/png/jpeg;base64,' . base64_encode( $row['image'] ) . '" height="150" />'; This is showing up images great in firefox, safari and chrome, but in internet explorer it shows a nice red cross, and I assume it is because of the encoding? Does anyone know how to get working in internet explorer as well? Pretty urgent job! Much appreciated for your help! Hi, I have managed to get the code working to store a .jpg file in the database under the longblob type. Now all i have left to do is to retrieve that image and display it. So far i have this: list.php Code: [Select] while($r = mysql_fetch_array($sql)) { //for each record ... echo " <img src= getoutside.php?id='".$r[apartmentId]. " '> "; getoutside.php Code: [Select] <?php header("Content-type: image/jpg"); // act as a jpg file to browser $nId = $_GET['id']; include 'dbase.php'; //connect to database $sqlo = "SELECT outside FROM apartment WHERE apartmentId = $nId"; $oResult = mysql_query($sqlo); $oRow = mysql_fetch_array($oResult); $sJpg = $oRow["outside"]; echo $sJpg; ?> The result from this is a box with a red cross in it. Can anyone find a problem with this code please? Thanks Hi All, This is my first post on here. I'd really appreciate any help with this, it's driving me mad. I'm trying to create a form to save a image into a mySQL database. I have a website hosted by UK2.net which has a mysql db with a table called gallery(name (varchar 30), size (int), type varchar(30), thePic(mediumBlob)). I have a form with this: Code: [Select] <td><p><label>Pic: </label></td><td><input name="userfile" type="file" id="userfile" /></td></p> Which when submitted actions addImage.php. The code for this looks like this: Code: [Select] <?php $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); } $con = mysql_connect("localhost", "userName", "password") or die(mysql_error()); mysql_select_db("dbName", $con) or die(mysql_error()); $query = "INSERT INTO gallery (name, size, type, thePic) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } echo "<br>File $fileName uploaded<br>"; ?> I get the following error message: Quote Warning: fopen() [function.fopen]: Filename cannot be empty in /home/hiddenje/public_html/addImage.php on line 13 Does anyone know what this is about? I've been on out friend google and a lot of people seem to be pointing to permissions but I can't seem to apply it to my scenario and just can't get it to work. Im a developer by trade, but this is my first step into the...interesting world of PHP and mySQL. Again, I'd appreciate any help with this. I'd love someone to talk me through exactly what I'm missing or doing wrong. Thanks in advance. I have a base64 encoded image -> http://pastebin.com/698ES5t0
Im trying to export this as a png file.
$picture = {data on paste bin}; $picture = base64_decode($picture); file_put_contents('/home/picture.png', $Picture);Now this creates a file picture.png and i can open it in Preview/Gimp etc. However, if i upload the file to my website, the image does not render in chrome/firefox, however it does render in Safarai. It seems that there is no height/width/depth data. Okay, so here is the deal. Have a table which stores image as blob files. Now i want to read the image width and height directly from the blob field. Is this possible and if yes, how? Things i tried so far; list($size[0],$size[1],$type, $attr) = getimagesize('image.php?i=26ddd45b02859e836d13d4b9fde34281'); print_r($size); $img = 'image.php?i=26ddd45b02859e836d13d4b9fde34281'; echo imagesy($img); image.php grabs the image from DB and show's it with header("Content-type: image/jpg"); It works for just showing the images with the <img> tag. Any ideas of help would be great! Hello, Five images will be displayed inside a division. There will be a previous and next button/link. If someone click the next button the next image will be added in that div and the first image will be gone from that div. The previous button/link will do the same thing. Is it possible with php? I am confused if it's a javascript or ajax question. Thanks. Would like to be able to click on a radio button that represents an image. Once selected and submitted, have that image display on another page. I have an idea, but need some guidance. BTW, is using php only doable? Is there a simpler or more elegant way to do this? Thanks all! Hi, I wonder whether someone may be able to help me please. Through articles I've read on the Interent I've put together the code shown below which allows a user to upload, view and delete image files from a mySQL database. Code: [Select] if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!isset($_POST["action"])) { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(No title provided';// use (empty title) string if (isset($_FILES['photo'])) { @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'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: Image Uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion elseif($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb { $msg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />"; } if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $imageid = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE imageid=$imageid"); $msg = 'Photo deleted'; } if (isset($_POST['view'])) // If used selected some photo to delete { // in 'uploaded images form'; $imageid = intval($_POST['view']); mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); if(mysql_num_rows($result) == 1) { $image = $row['myimage']; header("Content-type: image/gif"); // or whatever print $image; exit; } } } else { $imageid = intval($_POST['del']); if ($_POST["action"] == "view") { $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data FROM {$table} WHERE imageid=$imageid LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $imagetime, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than $send_304 = true; // imagetime } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } else if ($_POST["action"] == "delete") { $imageid = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE imageid=$imageid"); $msg = 'Photo deleted'; } } } ?> The problem I'm having is around the error message shown if the File Size is over the prescribed limit. The part of the script that deals with this starts with the line: Code: [Select] elseif($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb Even though the file upload may fail because of the size of the file I receive the 'Error: unknown file format' message, and I'm not sure why. I'm certainly no expert when it comes to PHP, so perhaps my lack of knowledge is letting me down. But I just wondered if someone could perhaps take a look at this please and let me know where I'm going wrong. Many thanks Chris Hi I have create a script that adds a image as blob successfully, however now I want to create a thumbnail, I have the following code; can someone help... # open and code into blob $fp = fopen($safename, 'r'); $content = fread($fp, filesize($safename)); $thumb = $content; $content = addslashes($content); fclose($fp); # resize accordingly... $thumb = new resize($content, $width, $height, 300); # the class that does the resizing (WHERE I THINK ITS GONE WRONG) class resize { public $new_image_blob = ""; function __construct($blob, $width, $height, $amount) { # the maximum width and height as set by the user $thumb_height_max = $amount; $thumb_width_max = $amount; # maintain aspect ratio landscape or portrait if($width < $height) { $new_width = ($thumb_height_max / $height) * $width; $new_height = $thumb_height_max; $needtoresize = ($height < $thumb_height_max); } else { $new_width = $thumb_width_max; $new_height = ($thumb_width_max / $width) * $height; $needtoresize = ($width < $thumb_width_max); } # now that we have the new width and heightwe need to resize the blob $im = imagecreatefromstring($blob); $thumb = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($thumb, $im, 0, 0, 0, 0, $new_width, $new_height, ImageSX($im), ImageSY($im)); $this->new_image_blob = addslashes($thumb); } } # then the query below adds the code (the original blob goes in correctly (ablob) but bblob (the resized blob doesn't)) $iS = "INSERT INTO $tableb (pal, afield, bfield, cfield, dfield, efield, ffield, gfield, ablob, bblob, cblob, dblob) VALUES ('6', '$fk', '$filename', '$size', '$fileExtension', '$width', '$height', '$orientation', '$content', '$thumb->new_image_blob', '$four', '$two')"; Hi there, How could I get the value of every 4 bytes of a BLOB? Additionally, how can I add an item to the end of a BLOB and store it back in the database? Cheers, George Hi, I have a MySQL database with BLOB data (MS Word files, Excel, PowerPoint, PDF etc.). I have a show_file function that assembles the blobs to send the file to the browser. It's been working great for a decade. Now, I am looking to filter the data against XSS vulnerabilities, much like I do with strings using htmlentities(). How do you go about doing that with BLOB data? I'm assuming htmlentities() will strip out characters from the BLOB data that will render the file unusable, correct? Here is my function: function show_file( $fileID ) { $nodeList = array(); $fileInfo = get_record( 'FileList', 'fileID', $fileID ) or trigger_error( 'Not a valid file ID: ' . $fileID ); // Pull list of inodes $nodes = get_recordset( 'FileData', 'fileID', $fileID, 'blobID' ); if ( !$nodes ) { trigger_error( 'Failure to retrieve file inodes: ' . mysql_error() ); } while ( $node = mysql_fetch_array( $nodes ) ) { $nodeList[] = $node['blobID']; } // Send down the header to the client if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE' ) ) { header( 'Cache-Control: public' ); } header( 'Content-Type: ' . $fileInfo['fileType'] ); header( 'Content-Length: ' . $fileInfo['fileSize'] ); header( 'Content-Disposition: attachment; filename=' . $fileInfo['fileName'] ); // Loop thru and stream the nodes 1 by 1 for ( $z = 0; $z < count( $nodeList ); $z++ ) { $query = 'SELECT fileData FROM FileData WHERE blobID = ' . $nodeList[$z]; if ( $result = mysql_query( $query ) ) { echo mysql_result( $result, 0 ); } else { trigger_error( 'Failure to retrieve file node data: ' . mysql_error() ); } } } So, I am looking to do something like echo mysql_result( htmlentities($result), 0 ); Thanks for any help you may provide, George. So I have a database with BLOBs (jpeg images). I also have a handy PHP page to display the image given an image ID. This page works fine, by getting the data, setting the content-type header to "image/jpeg", and echoing the data. Now here's the rub: I need the page to also display other information, in text / html format (i.e. show image, and below it show time the image was taken and other information also stored in the database. Because the content-type header has been set as "image/jpeg", I can't display this additional content. How can I make this work? Thanks! Hey there, need some help badly. I'm trying to get the size of the BLOB data in mysql. Did a search and there are like no tutorial on this. Only relevant info was from this page, at the far bottom, it just wrote this (below code). But the writer did not explain how to use it. SELECT OCTET_LENGTH(content) FROM BloBTest WHERE filename='myimage.png' I just give it a trial an error, wrote this, but did not work. $LENGTH = mysql_query("SELECT OCTET_LENGTH(blobdata) FROM thedatabase WHERE id = 'selected_id'"); echo $LENGTH; Please help.... |