PHP - Using File Put Contents With Blob Image Data
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. Similar TutorialsHi, 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 Hello, I am storing files that my users upload to the website as a blob in mysql database. Here is the code that does uploading: $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 = mysql_real_escape_string($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $query = mysql_query("INSERT INTO documents (idapplicant, fileType, fileSize, fileData, fileName) VALUES ('$idapplicant','$fileType','$fileSize', '$content','$fileName')",$db); Here is the code for download: echo "File found:".@mysql_result($result, 0, "fileID"); //always correct $data = @mysql_result($result, 0, "fileData"); $name = @mysql_result($result, 0, "fileName"); $size = @mysql_result($result, 0, "fileSize"); $type = @mysql_result($result, 0, "fileType"); header("Content-length: $size"); header("Content-type: $type"); header("Content-Disposition: attachment; filename=$name"); echo $data; I can upload/download files no problem. However, I noticed problem with GIF files. All GIF files are just dark screen after downloading. All other files (PDF, JPEG) looked just fine. I compared files (before upload and after download) in HEX editor and found that the first byte on all files is set to A0 (it is added in front of all the data) and the last byte is deleted! I have tried: $content = addslashes($content); instead of: $content = mysql_real_escape_string($content); with the same results I also tried removing this line of code and in that case no file would be uploaded at all! Any idea? Thank you 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 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 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; ?> 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] $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 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. 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! I using.. 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 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. 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] 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! I need some help...I want to read the contents of a file into a variable and then insert/write that content into another file. Code: [Select] $handle = fopen($create_mysql_db_url, "rb"); $contents = fread($handle, filesize($create_mysql_db_url)); fclose($handle); $userFileName = $_POST['mysqluser'] . time() . ".php.txt"; $fhandle = fopen($userFileName,"wb"); fwrite($fhandle, $contents); fclose($fhandle); $fh = fopen($userFileName,"wb"); $contents = fread($fh, filesize($userFileName)); $content = preg_replace("/###USERNAME###/", $_POST['mysqluser'], $contents); $content = preg_replace("/###PASSWORD###/", $_POST['mysqlpass'], $content); fwrite($fh, $content); fclose($fh); please help Hello friends, if i have the following $path = "http://*site*.com"; why can't i write the following $ORGtext= file_get_contents('$path'); it works only if i write $ORGtext= file_get_contents('http://*site*.com'); but i want to put $path instead of the url at file_get_contents is it possible and if yes then how ? thank you Hello, I have a simply query that will if a simple two different things: Code: [Select] $cssyn = mysql_query("SELECT `12` FROM `12345` WHERE `abc` = '$_SESSION[number]'"); $cssy = mysql_fetch_row($cssyn); if($cssy[0] == "YES") { echo "Yes"; } else { echo "No"; } The YES or NO result is stipulated earlier on so thats not the problem. But basically before I added the if statement simply would have echoed a table with all the rows etc from another query. However I would like to give the user a choice between echoeing the results into one table or a neater two. I have separated the code for the table and the queries into two separate files but say if I use: file_get_contents then it just prints the HTML and doesnt actually populate it will the queried parts. Nor if I use something like include() then it wont echo anything, which it wouldnt unless called so what I am asking is: Is there a way to get EVERYTHING from the file if the answer is YES or the other file if NO. eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. I'm trying to extract the contents of a zip file to a folder. I found the ZipArchive class and followed the examples to get it to work for the most part. But I want to extract the files in the folder inside the zip file but leave the folder out. So it should extract just the files to my given destination. I found this on php.net. Code: [Select] If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder). <?php $path = 'zipfile.zip' $zip = new ZipArchive; if ($zip->open($path) === true) { for($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); $fileinfo = pathinfo($filename); copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']); } $zip->close(); } ?> For some reason that 'copy' line is not working for me. Obviosly I've changed the variables in the line to the correct variables. Can someone help me out. Thanks Mike i am trying to do a "file get contents" from the following website http://www.bet365.com/home/ It is necessary to input your account username and password here, and then I want to get the contents of this page http://www.bet365.com/extra/en/results-and-archive/results/?Fromdate=13%2f09%2f2014+00%3a00&SearchPath=result&FixtureId=46827110&Period=99&ChallengeId=26278650&CompetitionId=999999&SportId=1&SportDesc=Soccer&Todate=14%2f09%2f2014+00%3a00&LanguageId=1&Zoneid=1 I have tried a couple of scripts but just can't seem to get it to work. I have tried $context = stream_context_create(array( 'http' => array( 'header' => "Authorization: Basic " . base64_encode("$username:$password") ) )); $data = file_get_contents($url, false, $context); echo $data; with the username and password and url entered as variables. but get the message Warning: file_get_contents(http://www.bet365.com/extra/en/results-and-archive/results/?Fromdate=13%2f09%2f2014+00%3a00&SearchPath=result&FixtureId=46827110&Period=99&ChallengeId=26278650&CompetitionId=999999&SportId=1&SportDesc=Soccer&Todate=14%2f09%2f2014+00%3a00&LanguageId=1&Zoneid=1) [function.file-get-contents]: failed to open stream: HTTP request failed! in "myscript's address" on line 13 Maybe i don't need to visit the homepage first to log in? Any ideas please? Thank youapologies for the message being in code quotes, I wrote it in Word but then couldn't paste it, even using the special Word paste button. Hope the message comes out ok. Thank you. |