PHP - Checking For Image - Redundant Code?
Thanks to everyone's earlier help, I pretty much have my "Upload a Photo" module done.
However, I am wondering if the following code snippet can be streamlined? Do I really need to check for Width and Height when above I look at if ($imageDetails = getimagesize($tempFile)){?? // ******************** // Check File-Type. * // ******************** if (empty($errors)){ if ($imageDetails = getimagesize($tempFile)){ // Image-Array Exists. $width = $imageDetails[0]; $height = $imageDetails[1]; $imageType = $imageDetails['mime']; // IS IT REDUNDANT TO CHECK THE DIMENSIONS??? // ************************ // Check for Dimensions. * // ************************ if ($width && $height){ // Width and Height Exist. // File is Image. // ************************ // Determine Image-Type. * // ************************ if ($imageType !== 'image/gif' && $imageType !== 'image/jpeg' && $imageType !== 'image/png'){ // Invalid Image-Type. $errors['upload'] = 'Image-type must be either GIF, JPG, or PNG.'; }else{ // Valid Image-Type. // Continue Processing Upload... }//End of DETERMINE IMAGE-TYPE }else{ // File Not Image. $errors['upload'] = 'Only Images can be uploaded (i.e. GIF, JPG, or PNG).'; }//End of CHECK FOR DIMENSIONS }else{ // No Image-Array. // File Not Image. $errors['upload'] = 'Only Images can be uploaded (i.e. GIF, JPG, or PNG).'; } }//End of CHECK FILE-TYPE What do you think? I am leaning towards taking the second check out for brevity... Debbie Similar TutorialsI found the code below which checks to make sure something the user entered into a text field is an actual URL. I am looking to confirm that something a user enters is an actual link to an IMAGE, so does anyone know how I could adjust this code below to do that? Basically, this code below would accept http://monkeys.com AND http://monkeys.com/images/monkey.jpg. I want to alter the code so that http://monkeys.com would NOT be accepted since it's not an image. Essentially, I want to make sure whatever the user enters ends with .jpg, .gif or .png. Anyone know how to do this? Code: [Select] url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/, "alertText": "* Invalid URL" } My code looks something like this: //section one apples = $POST ['apples'] donuts =$POST['donuts'] SQL= blah blah blah //section two INSERT (apples, donuts) VALUES ($apples, $donuts) etc Is "section one" necessary to have in my script, or is redundant since the values are indicated in my results statement? I need clarification from people who know this stuff well. Thanks Hello Everyone, I m making an attendance application. I have an issue with following code, Code: [Select] <?php session_start(); require_once("conf.php"); mysql_select_db('site'); $subjects=$_GET['sublen']; $username=$_SESSION['user']; for($i=1;$i<=$subjects;$i++) { $subject=$_GET[',Sub'.$i]; $query="INSERT INTO Subjects(id,Subjects,User,Classs) VALUES($i,'$subject','$username','F.Y.B.Sc')"; $true=mysql_query($query) or die("Cannot Store subjects".mysql_error()); } ?> <html> <head> <link href="../css/style.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="../js/jquery.js"></script> </head> <body> <div id="main"> <div id="logo"> KiMi... </div> <div id="header"> <ul> <li><a href="index.html">Home</a></li> <li><a href="php/subjectsTable.php">Create Subjects</a></li> <li><a href="html/form.html">Contact Us</a></li> <li><a href="html/register.php">Register!</a></li> </ul> </div> <div id="nav"> </div> <div id="content"> <?php if($true) { echo "<div id='dynamicDiv'>"; echo "<div> Subjects stored Successfully!</div></br></br>"; $query="SELECT * FROM Subjects Where User='$username'"; $result=mysql_query($query) or die("Cannot Fetch Data"); echo "<table id='table'>"; echo "<tr><td> </td><td>Subjects</td><td>Class</td></tr>"; while($row=mysql_fetch_array($result)) { echo "<tr><td><input type='checkbox' name='box[]'/> </td>"; echo "<td>"; echo $row['Subjects']; echo "</td>"; echo "<td>"; echo $row['Classs']; echo "</td>"; echo "</tr>"; } echo "</table>"; echo "</div>"; } ?> </div> <div id="footer"> © Copyright Amit K. Goda 2011-2012 </div> </div> </body> </html> In the above code i m storing data into database which has been passed into $_GET array. The Code is this Quote <?php session_start(); require_once("conf.php"); mysql_select_db('site'); $subjects=$_GET['sublen']; $username=$_SESSION['user']; for($i=1;$i<=$subjects;$i++) { $subject=$_GET[',Sub'.$i]; $query="INSERT INTO Subjects(id,Subjects,User,Classs) VALUES($i,'$subject','$username','F.Y.B.Sc')"; $true=mysql_query($query) or die("Cannot Store subjects".mysql_error()); } ?> the data is stored but the issue is, since i have data coming in $_GET array when i reload my page the same data is stored again inmy database. So any suggesstions how can i avoid that??? Any Help will be highly appreciated Hi, I wrote a simple code to check to see if the user filled in the name field, but when I uploaded the file, it just displays the code. here 's the code. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <?php $errors=array(); if(isset($_POST['submit'])) { validate_input(); if(count($errors) !=0) { display_form(); } else { display_form(); } } function validate_input() { global $errors; if($_POST['name'] == " "){ $errors['name']="dipshit, put your name"; } ?> <form action="" method="post" name="test"> Name: <input name="name" type="text" size="10" maxlength="15" value="<?php echo $_POST[name]; ?>"/><br /> <?php echo $errors['name']; ?> <input name="submit" type="button" value="submit" /> </form> </body> </html> Hi All, I'm having a major mind blank, and can't find anything in the previous posts resolving what I'm after. I'm setting $searchtext = $_POST['searchtext']; I want to check $seachtext is not null. I've seen isset($searchtext) but it doesn't solve my problem. Basiclaly; I want an if statement to say if(isset($searchtext)) {......} Thoughts? Hello all, I'm currently doing this Facebook connect module for my website. With the FBconnect, it creates a user profile on my mysql, which stores only the Facebook userid, the full name, and the thumbnail url of this user. Currently the code works well except for this 'image url checking'. this is my fb profile image url: http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs349.snc4/41540_772137439_5612219_q.jpg when I've added a 'XXX' at the back ( http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs349.snc4/41540_772137439_5612219_qXXX.jpg ). It returns a blank instead. On Facebook, some accounts are not genuine and they might the deleted sooner or later. So I'm trying to figure out a php script or functions which detect if the image is not the 'XXX' version. I've tried using getimagesize() or file_get_contents() but still won't work. any ideas? Hi , I got "High Slide Script" for making photogallery .. The problem is that code has no admin panel to upload images and their description . All you make that you write image path into html code of its index page.. I thought to make admin panel by a small database you enter the image path uploaded and description . and the code has a loop to read this data throught a php code . I attached what I made . The problem is : why my images doesn't appear ??? NB: the original script in the file named : highslide-custom-example.htm my code is in the file : highslide-custom-example.php I attached the DB also.. Here is the attachments : http://www.seed-share.com/6mghkdpg0ywj Thanks Good afternoon: I have added a database field to a table that has quiz questions in it. the field I have added is for images and I have entered the image url that is stored on the server in an image folder. Please could you tell me how I can include the image in the request by adding to the code below: $Questions = $DB->query("select * from ".TABLE_PREFIX."quiz_questions where q_forquiz='{$Quiz['qid']}' order by qqid"); while($Question = $DB->fetch_array($Questions)){ $Q[$Question['qqid']] = $Question; } Fields in table quiz_questions: qqid q_question q_type q_params q_forquiz q_questionimages - This is the field I added. Thank you for helping. Amilo Hello,
I have a website called http://flappycreator.com/ where users can upload multiple images to create their own version of Flappy Bird. As a result of this I created a PHP page that takes a GET param to create a preview image of their game to display in various locations on the website.
Here is an example:
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
My issue is, I have given my users the ability to upload PNGs or JPGs and trying to figure out reliable code to display the preview has become a huge hassle. In the example above the Pac-Man character shows a white background but when you play the game, it is actually transparent. In other situations I am getting extremely bad color distortion. The code I have provided is my final attempt after a ton of trial-and-error and the PNG imagealphablending() and imagesavealpha() commands have shown me the best results, however I don't know what they do.
Please help! Thanks.
<?php $bird_picture = "default/bird.png"; $tube1_picture = "default/tube1.png"; $tube2_picture = "default/tube2.png"; $ground_picture = "default/ground.png"; $bg_picture = "default/bg.png"; // If an id is set, then reset values if (isset ( $_GET ['id'] )) { require ('XXX.php'); $db = new DBAccess (); $query = "SELECT * FROM XXX WHERE XXX = '{$_GET['id']}'"; $result = $db->query ( $query ); $num_results = $result->num_rows; $row = mysqli_fetch_array ( $result ); if ($num_results != 0) { if ($row ['bird_picture'] != "") { $bird_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bird_picture']; } if ($row ['tube1_picture'] != "") { $tube1_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube1_picture']; } if ($row ['tube2_picture'] != "") { $tube2_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube2_picture']; } if ($row ['ground_picture'] != "") { $ground_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['ground_picture']; } if ($row ['bg_picture'] != "") { $bg_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bg_picture']; } } } $temp = explode(".", $bg_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $background = imagecreatefromjpeg($bg_picture); } else { $background = imagecreatefrompng($bg_picture); // Turn off alpha blending and set alpha flag imagealphablending($background, true); imagesavealpha($background, true); } $temp = explode(".", $ground_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $ground = imagecreatefromjpeg($ground_picture); } else { $ground = imagecreatefrompng($ground_picture); // Turn off alpha blending and set alpha flag imagealphablending($ground, false); imagesavealpha($ground, true); } $temp = explode(".", $bird_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $bird = imagecreatefromjpeg($bird_picture); } else { $bird = imagecreatefrompng($bird_picture); // Turn off alpha blending and set alpha flag imagealphablending($bird, false); imagesavealpha($bird, true); } $temp = explode(".", $tube1_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube1 = imagecreatefromjpeg($tube1_picture); } else { $tube1 = imagecreatefrompng($tube1_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube1, false); imagesavealpha($tube1, true); } $temp = explode(".", $tube2_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube2 = imagecreatefromjpeg($tube2_picture); } else { $tube2 = imagecreatefrompng($tube2_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube2, false); imagesavealpha($tube2, true); } imagecopymerge($background, $tube1, 200, -200, 0, 0, 52, 320, 100); imagecopymerge($background, $tube2, 200, 200, 0, 0, 52, 320, 100); imagecopymerge($background, $ground, 0, 320, 0, 0, 336, 112, 100); imagecopymerge($background, $bird, 70, 190, 0, 0, 36, 26, 100); header('Content-Type: image/png'); imagepng($background); # Destroy imagedestroy($background); imagedestroy($ground); imagedestroy($bird); imagedestroy($tube1); imagedestroy($tube2); ?>Attached Files preview.php 3.31KB 1 downloads Well here is the original code in my script file, and it has a background color Green now: [/php]$article_content = "<center><table style='color: #FFFF31; background: Green; width: 400px; border: 1px solid #9BDDFF;'><tr><td><i><b><u>Welcome to Mysidia City's fishing pool</b></u></i><br><br><br> Before you actually begin your fishing career, I'd strongly recommend you to doublecheck if you have a fishing rod already since it is apparently required for every fisherman here. <br><br><br><a href='fishing.php?act=1'>Enter</a> the fishing pool now if you have a fishing rod already or <br>Visit this <a href='fishingquiz.php'>Page</a> to take the fishing quiz and earn yourself an old rod to begin with. <td></tr></table><br><center><img src='picuploads/other/lakeofrage.png'></center>";[/php] Now I wish to replace the background color with a background image, what should I do? The image url is provided below: http://www.pokemansion.net/picuploads/other/seadrabg.png I have an image upload script where I am trying to compress an image to a lower file size. The code works. The image uploads to the directory with the correct name as intended. The only thing is that it's not compression the image as it should be. The size of the new image is the same as the old image. Here's my code. Can you spot what i'm doing wrong? // FUNCTION FOR COMPRESSION function compress_image($source_url, $destination_url, $quality) { $info = getimagesize($source_url); if($info['mime'] == 'image/jpeg') { $image = imagecreatefromjpeg($source_url); } else if ($info['mime'] == 'image/gif') { $image = imagecreatefromgif($source_url); } else if ($info['mime'] == 'image/png') { $image = imagecreatefrompng($source_url); imagejpeg($image, $destination_url, $quality); } return $destination_url; } // FORM SUBMIT CODE $errors = array(); $db->beginTransaction(); if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) { if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) { // GENERATES A 10 CHARACTER STRING TO BE USED FOR AN IMAGE NAME $random_name = generateRandomString(10); $global_user_id = 10; $url_project_id = 5; $target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); if(!is_dir($target_dir)){ mkdir($target_dir, 0775, true); } // RESIZE IMAGE $pathname = $_FILES["fileToUpload"]["tmp_name"]; $resized_image = compress_image($pathname, $random_name, 40); $new_file_path = $target_dir . $resized_image . '.' . $imageFileType; // Check if image file is a actual image or fake image $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { // echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { $errors[] = 'File is not an image!'; $uploadOk = 0; } // Check if file already exists if (file_exists($new_file_path)) { $errors[] = 'Sorry, file already exists!'; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 5000000) { $errors[] = 'Sorry, your file size is bigger than 5mb!'; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") { $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!'; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if($uploadOk == 0) { $errors[] = 'Sorry, your file was not uploaded!'; // if everything is ok, try to upload file } else { if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_file_path)) { // SUCCESS MESSAGE } else { $errors[] = 'Sorry, there was an error uploading your file!'; } } } else { $errors[] = 'You must upload an image!'; } } if(empty($errors)) { $db->commit(); header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); exit; } else { $db->rollBack(); }
I've been working on this site that allows users to upload images to the server... the code i have right now basically uploads the file to the server and then resizes it and makes a new copy of it... Upuntil now it was working flawlessly, however now i'm getting this error: Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 144 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'images/projects/porncheck_star.png' is not a valid JPEG file in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 144 Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 162 Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 165 In order for you guys to understand the error here's the code i'm using //move file to the folder before resizeing move_uploaded_file($_FILES['image']['tmp_name'], $target); //resize the image and add to server $source_pic = $target; $final_pic = $dir.$final_img_name; $max_width = 800; $max_height = 600; $src = imagecreatefromjpeg($source_pic); list($width,$height)=getimagesize($source_pic); $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height) ){ $tn_width = $width; $tn_height = $height; }elseif (($x_ratio * $height) < $max_height){ $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; }else{ $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } $tmp=imagecreatetruecolor($tn_width,$tn_height); imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height); imagejpeg($tmp,$final_pic,80); imagedestroy($src); imagedestroy($tmp); list($width, $height, $type, $attr) = getimagesize($final_pic); Keep in mind that this code was working perfectly and now for some reason its not working anymore, and no i have not touch it at all nor i have done nay edits to this code Hope someone can help me out because i have no idea what this could be. Thanks I'm trying to create a series of images on a page but the code won't run. (left table code out): <body> <?PHP /// fyi, the image_link field contains, e.g., artistfoldername/imagefilename.jpg $path = "artWorkImages/"; $art_id ='2'; $QUERY="SELECT art_title, about_art, image_link FROM artWork WHERE art_id = '$art_id'"; $res = mysql_query($QUERY); $num = mysql_num_rows($res); if($num>0){ while($row = mysql_fetch_array($res)){ $artist_name = $row["art_title"]; $about_art = $row["about_art"]; $image_link = $row["image_link"]; print "<img src=$path.$image_link/>"; } } ?> </body> Thanks Allen I'm tired and just about given up. Can anybody help me? Code: [Select] <?php $objConnect = mysql_connect("localhost","","root") or die(mysql_error()); $objDB = mysql_select_db("sdf"); $pic2 = "SELECT * FROM images"; if (!isset($_GET['Page'])) $_GET['Page']='0'; $pic1 = mysql_query($pic2); $Num_Rows = mysql_num_rows($pic1); $Per_Page = 16; // Per Page $Page = $_GET["Page"]; if(!$_GET["Page"]) {$Page=1;} $Prev_Page = $Page-1; $Next_Page = $Page+1; $Page_Start = (($Per_Page*$Page)-$Per_Page); if($Num_Rows<=$Per_Page) {$Num_Pages =1;} else if(($Num_Rows % $Per_Page)==0) {$Num_Pages =($Num_Rows/$Per_Page) ;} else {$Num_Pages =($Num_Rows/$Per_Page)+1; $Num_Pages = (int)$Num_Pages;} $pic2 .=" order by thumbnailID ASC LIMIT $Page_Start , $Per_Page"; $pic1 = mysql_query($pic2); $cell = 0; $link1 = "SELECT * FROM images"; $result_link1 = mysql_query($link1); $link = mysql_fetch_array($result_link1); $alt1 = "SELECT * FROM images"; $alt = mysql_fetch_array(mysql_query($alt1)); echo ' <div id="tablediv"> <table border="0" cellpadding="17" cellspacing="0" class="table"> <tr>'; while($pic = mysql_fetch_array($pic1)) { if($cell % 4 == 0) { echo '</tr><tr>'; } if($cell == 2) { echo ' <td> fillerspace </td>'; } elseif ($cell == 3) { echo ' <td> Fillerspace2 </td>'; } else { echo ' <td> <a href="/' . $link["link"] . '.php"> <div class="image"> <img src="https://s3.amazonaws.com/image/' . $pic["pic"] . '.png" alt="' . $alt["alt"] . '" height="200" width="200" /> </div> </a> </td>'; } $cell++; } echo '</tr></table></div>'; ?> Basically, there are a couple of faults with this code. I didn't include the pagination part, but there is, for simplicity. But right now, when I insert a new record such as this: INSERT INTO `images` VALUES (' ', 'blog', 'yo', '6', 'hello', '2011-02-15T07:24:17Z') The columns go in order of thumbnailID, folder, link, pic, alt, and time.^^^^^^^^ several problem arises. One, the new record is not displayed as the newest entry on my site. So the record is actually placed in one of the paginated pages. How can I reverse the order? The other thing is, it seems like my pic column is the only thing being understood. You see, when I inserted the above record, I checked my site and saw the pic 6, but the link wasn't 'yo', and the alt wasn't 'hello'. Why is that? By the way, my host is awfully terrible. Maybe it's just having a major delay in reading the link and alt? I don't know. That would be the only reasonable answer, unless my code is off. Thank you, and I'll check 10hours from now. Ok so I followed Buddski's advice to use MIME for the attatchment. (thanks for the help by the way, definitely headed in the right direction now.... i think...) The image now successfully uploads to temp_folder on submit, the email is then delivered with correct text variables (name, phone, address etc.). However, instead of their being an image included - there is just raw code. If anyone could help with the final fix you may just save my sanity! Thanks. Code: [Select] <?php ini_set("sendmail_from", "darren@mywebsite.co.uk"); ini_set("SMTP", "smtp.myhosts.co.uk"); // Subject and Email Destinations // $emailSubject = 'Work Email!'; $webMaster = 'darren@mywebsite.co.uk'; // Gathering Data Variables // $name = trim($_POST['name']); // create a unique boundary string // $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // Add the headers for a file attachment // $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // Add a multipart boundary above the plain message // $message ="This is a multi-part message in MIME format.\n\n"; $message.="--{$mime_boundary}\n"; $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n"; $message.="Content-Transfer-Encoding: 7bit\n\n"; $message.= "Name: ".$name."\n"; //The file type of the attachment // $file_type = 'text/csv'; // The place the files will be uploaded to (currently a 'files' directory) // $upload_path = './uploads/'; // Get the name of the file (including file extension) // $filename = $_FILES['userfile']['name']; // Get the extension from the filename // $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Configuration of File Uploaded // $allowed_filetypes = array('.jpg','.JPEG','.jpeg','.gif','.bmp','.png'); $max_filesize = 2000000; (move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)); //This attatches the image file to the email // $message .= chunk_split(base64_encode(file_get_contents($upload_path . $filename))); // Send the Email with the attatchment. $success = mail($webMaster, $emailSubject, $message, $headers, "-fdarren@dsinteriorsltd.co.uk"); ?> >>>is returning this to my email... Code: [Select] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="==Multipart_Boundary_x9cbb390d8be528476c5423025ed1e4ccx" This is a multi-part message in MIME format. --==Multipart_Boundary_x9cbb390d8be528476c5423025ed1e4ccx Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Name: darren /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEB........................................................... ..........this code goes on like this for ages. I m trying to fetch a image from mysql (blob) with header..here is my coding..."<?php include("db.php"); $query=mysql_query("select * from table where id='3' "); $row=mysql_fetch_array($query); $r=$row['image']; header("content-type:image"); echo $r; ?>" i want to fetch another fields from the database....but when i try to echo another fields...the page shows error or it does not echo other fields of database....please help me...how can i resolve it...i want to fetch other fields from database,like'username'password'firstname'lastname and image...thanks in advance... I have a PHP script that uploads images to a folder on my server (attachments folder). Currently the folder sits within my webroot and is publicly accessible (I have to use chmod 777 due to permissions issue). So, I created the "attachments" folder outside of my webroot (so that it is not publicly accessible), but I do not know how to set the path in the PHP code to upload it to that "attachments" folder outside of the webroot. As you see in the snippet of PHP code below, the code currently uploads the the "attachments" folder within the www (webroot) directory. How do I make it upload to the "attachments" folder OUTSIDE of the www (webroot) directory? foreach($files[$form] as $file){ $str = $file[1]; if (eval("if($str){return true;}")) { $_values[$file[0]] = $_FILES[$file[0]]["name"]; $dirs = explode("/","attachments//"); $cur_dir ="."; foreach($dirs as $dir){ $cur_dir = $cur_dir."/".$dir; if (!@opendir($cur_dir)) { mkdir($cur_dir, 0777);}} $_values[$file[0]."_real-name"] = "attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; copy($_FILES[$file[0]]["tmp_name"],$_values[$file[0]."_real-name"]); @unlink($_FILES[$file[0]]["tmp_name"]); }else{ $flag=true; if ($_isdisplay) { //$ExtFltr = $file[2]; //$FileSize = $file[4]; if (!eval("if($file[2]){return true;}")){echo $file[3];} if (!eval("if($file[4]){return true;}")){echo $file[5];} $_ErrorList[] = $file[0]; } } } This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=348759.0 Hi There, I want to add a picture to an existing user. The sql looks like: CREATE TABLE `klanten` ( `id` int(4) unsigned NOT NULL auto_increment, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `level` int(4) default '1', `filename` varchar(255) not null, `mime_type` varchar(255) not null, `file_size` int not null, `file_data` mediumblob not null, primary key (id), index (filename) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; id, username, password and level are allready filled in. Now i need some code to go with <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> process.php: <?php require_once 'database.php'; function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if (count($errors) == 0) { // no errors, so insert the image $query = sprintf( "insert into klanten (filename, mime_type, file_size, file_data) values ('%s', '%s', %d, '%s')", mysql_real_escape_string($image['name']), mysql_real_escape_string($info['mime']), $image['size'], mysql_real_escape_string( file_get_contents($image['tmp_name']) ) ); mysql_query($query, $con); $id = (int) mysql_insert_id($con); // finally, redirect the user to view the new image header('Location: view.php?id=' . $id); exit; } ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> to add to an existing user. Can somebody help me here? Best regards, Martijn |