PHP - How To Output Blob Images Through Php To Html ?
I'm trying to display my BLOB images in PHP and I've looked around in Google searches but everyone's examples seem to work for their specific code.
My table is called 'identification'. Here's my SQL: Code: [Select] == Table structure for table identification |------ |Field|Type|Null|Default |------ |//**id**//|int(11)|No| |image|blob|No| |image_width|char(220)|No| |image_height|char(220)|No| |image_type|enum('jpeg', 'pjpeg', 'png', 'gif')|No| |stickID|int(11)|Yes|NULL Similar TutorialsI have the two files below and want to separate php and html. How do I output forum.html with forum_post.html in it? I want to post as many forum_post.html as mysql_num_rows() says. Code: [Select] forum.html ====== <div> <form method="post"> <textarea name="text"></textarea> <input type="submit" /> </form> </div> <div> [b]???[/b] </div> Code: [Select] forum_post.html ====== <div> <h1>Title</h1> <p>Text</p> </div> I am trying to be true to the principle that logic and presentation should be kept separate. However, the only way to generate dynamic content and output is using something like PHP, so there is somewhat of a conflict. I just wrote this Function, and I am curious if it breaks the principle above... /** * Returns Online Status Indicator Markup * * Takes User's Last Activity and determines the User's Online Status. * Returns HTML for appropriate Online Status Indicator. * * @param DateTime $lastActivity MySQL DateTime format (yyyy-mm-dd hh:mm:ss) * @return string */ function getOnlineStatus($lastActivity){ // strtotime() converts DateTime format (yyyy-mm-dd hh:mm:ss) into a Unix Timestamp (seconds). // time() is current time measured in the # of seconds since Unix Epoch (January 1 1970 00:00:00 GMT). $minutesOnline = (time() - strtotime($lastActivity))/60; // Determine Online Status. if ($minutesOnline < 15){ // Member Online $indicator = '<img src="/images/Light_Green_10.png" width="10" alt="Member Online" /><br />'; }else if ($minutesOnline < 30){ // Member Idle $indicator = '<img src="/images/Light_Yellow_10.png" width="10" alt="Member Idle" /><br />'; }else{ // Member Offline $indicator = '<img src="/images/Light_Gray_10.png" width="10" alt="Member Offline" /><br />'; } return $indicator; }//End of getOnlineStatus Thanks, Debbie i'm trying to get a php database to output/display on a html webpage and have no results from cutting and pasting code from online tutorials i'm saving to a file with a htm extension i believe i have the connection data right: $db_host = 'server'; $db_user = 'username'; $db_pwd = 'password'; $database = 'database'; $table = 'table'; if (!mysql_connect($server,$username,$password)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); $result = mysql_query("SELECT * FROM table") or die(mysql_error()); Can someone please help me? send code? tell me what i'm doing wrong? Thanks I am trying to make PHP output a file in html and using the following code. Code: [Select] <?php readfile("./1/index.html"); ?> ... but it isn't working. How would I get PHP to output a file as HTML? Hi guys I am new here I have had a search around and can't really find out how to do this. Its quite difficult for me to explain and I am really new to PHP / mySQL - just starting out really. I hope to learn from doing small projects like this and seeing how it gets done. So I have a mySQL DB with two different tables - one is called "notesnew" the other is called "users". I have modified a common tutorial on how to make a "to do list" for what I am doing here. Basically users can login and post messages on this list as them self. Each user's post appears as a list item, showing their username, the time they posted the message and the message content. The message content, time and owner of the message is stored in the "notesnew" table. The list of user's, their passwords and their "avatar/profile" image URL location is stored in the "users" table. Now I am having trouble getting each user's avatar image from being output next to each of their posts. The part that is confusing me is being able to match up the username's post with their content that is display - because I am posting the user's name along with their post, based on the logged in "session name" as their username. So basically, all the content being listed is being displayed from the "notesnew" table. I need to somehow figure out what each user's profile image is based on what is stored against their entry in the "users" table. Here is the code I have so far. It is not working properly - it displays all content etc, but displays the avatar / image of the last user that has registered. Can anyone help me out here with some code that works, or pointers to try follow? I know the $finduserprofile part is incorrect in the way it goes through all user's and finds their profileimg, and that the image displayed next to each post is therefore incorrect (as it displays the last member to have registered's avatar, but its just that I don't know how else to do what I am trying to do. Code: [Select] <?php //Connect to the database $connection = mysql_connect('localhost', 'zzzz' , 'zzzzzzz'); $selection = mysql_select_db('zzzzz', $connection); $username = $_COOKIE['ID_my_site']; //Was the form submitted? if($_POST['submit']){ //Map the content that was sent by the form a variable. Not necessary but it keeps things tidy. $content = $_POST['content']; //Insert the content into database $ins = mysql_query("INSERT INTO `notesnew` (content, owner, dp_time) VALUES ('$content', '$username', NOW())"); //Redirect the user back to the members or index page header("Location:index.php"); } /*Doesn't matter if the form has been posted or not, show the latest posts*/ //Find all the notes in the database and order them in a descending order (latest post first). $find = mysql_query("SELECT * FROM `notesnew` ORDER BY id DESC"); $finduserprofile = mysql_query("SELECT * FROM `users` ORDER BY id DESC"); //Setup the un-ordered list echo '<ul>'; while($row = mysql_fetch_array($finduserprofile)) { $imagelocation = $row['profileimg']; //Continue looping through all of them while($row = mysql_fetch_array($find)) { $owner = $row['owner']; //For each one, echo a list item giving a link to the delete page with it's id. echo '<li>' . '<img src ="' . $imagelocation . '">' . $row['owner'] . ' said at ' . $row['dp_time'] . ': ' . $row['content'] . ' <a id="' . $row['id'] . '" href="delete.php?id=' . $row['id'] . '"><img src="delete.png" alt="Delete?" /></a></li>'; } } //End the un-ordered list echo '</ul>'; ?> I have noticed that today that some of the content that is saved from my form is printing random characters and crap. I am using htmlentities on the form input and it seems to be adding more rubbish. I am using the UTF-8 charset as a meta tag. Is this the correct way of using htmlentities? htmlentities($string, ENT_QUOTES, 'UTF-8') Also i noticed the other day with a problem I had that using htmlentities was replacing " with &" when i thought it should have just been " Hello! Im new here and want to start my new php carreer Well, I'm already working quite hard, but now I don't know what to do I've got it so far: <?php echo html::chars($message->text); ?> Is there any way I could modify the output, so it just displays the first 20 characters or so? Thank you all very much! I found this site: http://www.wallpaperama.com/forums/how-to-save-html-output-code-from-php-script-t6898.html it demonstrates how to save html output code from php script. here is an example: http://ads4agents.com/date.php I cant get it to work on my site...where is the correct place ad these: ob_start(); $HtmlCode= ob_get_contents(); ob_end_flush(); How can I get this to work in my php? view_ad.php <html> <body> <center> <br/> <h1>Apartment Reference #: <?php echo $_POST["reference"]; ?><br /></h1> <br/> <?php echo $_POST["application"]; ?>, <?php echo $_POST["deposit"]; ?><br /> <?php echo $_POST["pets"]; ?><br /> <br/> <?php echo $_POST["community"]; ?><br /> <?php echo $_POST["interior"]; ?><br /> <?php echo $_POST["amenities"]; ?><br /> <br/> <?php echo $_POST["contact"]; ?><br /> <a href="<?php echo $_POST['website'] ?>"><?php echo $_POST['website'];?></a><br/> <br/> <br/> <br/> </body> </html> Hi, Ok so I have the youtube url input working and it shows the video fine have a look at Code: [Select] http://www.cyberhost.me/test But now what I need is for the script to display the embed code needed for the user. This is the script: Code: [Select] <?php $text = $_POST["text"]; if (!isset($_POST['submit'])) { // if page is not submitted to itself echo the form ?> <html> <head> <title>Youtube code generator</title> </head> <body> <p>Copy and paste this url for example: http://www.youtube.com/watch?v=YdDIsImNfBY&feature</p><br/><br/> <form method="post" action="<?php echo $PHP_SELF;?>"> Youtube URL:<input type="text" size="50" maxlength="50" name="text"><br /> <input type="submit" value="submit" name="submit"> </form> <?php } else { //space anything that would get included in a link, add the space $text = str_ireplace(array("<br />","\n","\r"),array(" <br /> "," \n "," \r "),$text); $text = str_replace(" ", " ", $text); //explode the text by spaces $text_explode = explode(" ",$text); //loop replacing youtube links with embed codes, if not youtube embed return text foreach($text_explode as $words){ if (preg_match('~(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})~i', $words, $match)) { $vidid = $match[1];//the id $link = "http://youtu.be/$vidid";//short link to video //grab the title $visit_url = "http://gdata.youtube.com/feeds/api/videos/".$vidid; $doc = new DOMDocument; @$doc->load($visit_url); $link_title = $doc->getElementsByTagName("title")->item(0)->nodeValue; if($link_title == ""){ $link_title = "Click to watch video."; } //display a link echo "<h3><a href='$link' TARGET='_blank'>$link_title</a></h3>"; //embed the video echo "<div>"; echo "<object style='height: 390px; width: 640px'> <param name='movie' value='http://www.youtube.com/v/$vidid&fs=1'> <param name='allowFullScreen' value='true'> <param name='allowScriptAccess' value='always'> <embed src='http://www.youtube.com/v/$vidid&fs=1' type='application/x-shockwave-flash' allowfullscreen='true' allowScriptAccess='always' width='640' height='390'></object>"; echo "</div><br />"; } else { //keep the original words echo " $words "; } } } ?> The code I need displayed below is Code: [Select] <p> <img height="350" width="425" class="fw_media_youtube fw-parse" alt="YouTube-CODE PLACED HERE" src="http://thumbs.webs.com/Platform/mediaPreview.jsp?type=YouTube&id=CODE PLACED HERE"/></p> Where you see "CODE PLACED HERE" is where i need the video id placed and then for it to be displayed. Any idea how I would do this? Thanks in advance hi there, the code below is suppose to display something like the attachement "code2" but instead it displays something like attachement "code1" please assist in find what is wrong with my echo lines.
<?php $counter = 2; $sqlq="select * from state WHERE status = 0 "; $categorysqlq = mysql_query($sqlq); $varq = mysql_num_rows($categorysqlq); while($catfetchq = mysql_fetch_array($categorysqlq)) { $cnty = $catfetchq[0]; $sqllq="select * from vehicle WHERE country = '$cnty' "; $categorysqllq = mysql_query($sqllq); $numsql = "select * from branchaddr WHERE state = '$cnty' "; $numquery = mysql_query($numsql); $varqa = mysql_num_rows($numquery); $cntyfetchq= mysql_fetch_array($numquery); if($varq != 0){ if($counter == 2){ echo "<tr><td><a href=\"transport2.php?id=".$cntyfetchq['state'].">".$catfetchq[1]."(<span style=\"color:red\">".$varqa."</span>)</a></td>"; $counter--; } else{ echo "<td><a href=\"transport2.php?id=".$cntyfetchq['state'].">".$catfetchq[1]."(<span style=\"color:red\">".$varqa."</span>)</a></td></tr>"; $counter = 2; } } } ?>Attached Files code1.png 12.65KB 0 downloads code2.png 25.34KB 0 downloads Hi there,
My friend asked me to help him perform a task today and I was completely stumped as to how I should complete it. Being someone who is reasonably experienced with PHP programming I didn't think I would find it absolutely impossible to complete, maybe hard, but not impossible. So I wondered if someone would now be able to explain to me in order to assist me in expanding my knowledge how to complete this task.
https://www.dropbox....B8M6cr_z7a?dl=0
Here is a link to the files he sent me, please ignore the C++ section.
If anyone could help / begin to give an explanation please fire away. I feel so bad about myself for NOT knowing that I'm now motivated to learn more!
Many thanks!
Well I have a script that executes a scan on a system set to run infinitely, and I need it to echo out a message each time it loops through, but I don't want it to echo out the message with the next loop message below it, and the next one below that etc... I've tried using the flush(); function and been messing around with that with no luck. For security reasons I don't want to release any of the processing code, but here is the basic construction of the script: <?PHP ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** $RepeatIt = -1; for($g=1; $g!=$RepeatIt+1; $g++) { ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** $ScanMessage = ":.:.: SCANNING THE HITLIST FOR MOBSTER: ".$MobName." (SCAN #$g) :.:.:"."<br/><br/>"; echo $ScanMessage; ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** ***PROCESSING AND SCAN CODE*** } ?> At the moment it's returning: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #1) :.:.: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #2) :.:.: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #3) :.:.: :.:.: SCANNING THE HITLIST FOR MOBSTER: DEUS EX DESTROYER (SCAN #4) :.:.: So what I want it to do is just delete the scanning message and replace it with the next scan message so while running this script you would see just the number increment on the same line. Any suggestions? Thanks. 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 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, 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. 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 guys, I have a feeling the answer to this will be something incredibly simple I will be amazed I have failed to overlook but lets see. I have a database currently storing images as BLOB, it appears to be holding them fine, my upload page works fine to put images there etc The issue is coming when trying to display the images on an alternate page. I am using the code below, and it seems to recognize the field, however it is not displaying an image, it is displaying code. I have a feeling I need to add something to my headers to allow the page to show the images, but am not 100% sure. If someone could let me know what I am missing it would be great. Thanks in advance. Code: [Select] <? include "config.php"; $query = mysql_query("Select * FROM app_images WHERE image_month='test' ") or die(mysql_error()); while ($row = mysql_fetch_array($query)) { echo " " .$row['image']. " <br /><br />";} ?> |