PHP - Help With An Image Script
I have 23 products in a db, all with a unique ID that Im creating a user site for. Some of the items have 1 or 2 images and others have as many as 30 images.
In my db I have a field called "pics". All the images are saved as a .jpg, according to their id on the server. So if item 1 has 10 images the files a "1_001.jpg," "1_002.jpg," ect. How do I create a script that will display the correct amount of images based on the number in the db. I was going to do something like this: Code: [Select] if ($row['pics'] =="1") { $pictures = '<img src="pictures/'.$id.'_001.jpg" width="200" alt="" />'; } elseif ($row['pics'] =="2") { $pictures = '<img src="pictures/'.$id.'_001.jpg" width="200" alt="" /><img src="pictures/'.$id.'_002.jpg" width="200" alt="" />'; } elseif ($row['pics'] =="3") { $pictures = '<img src="pictures/'.$id.'_001.jpg" width="200" alt="" /><img src="pictures/'.$id.'_002.jpg" width="200" alt="" /><img src="pictures/'.$id.'_003.jpg" width="200" alt="" />'; } but that would just be retarded... Thank you! Similar TutorialsWell the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? Hi Guys, I am trying to disguise my php script as a .gif file for the purposes of a shopping cart. Basically, you click on the .gif which is placed on the page and it takes you to an image unless it has variables attached to it. Google use this for their checkout so I know this is possible. Does anyone have any ideas how I would go about doing this? Thanks in advance, Jacob. hello i have this php code to show the last image upload in a folder and the result is this http://theplattan.com/screenlive2/Screenshooter2.php this code must be in the same image folder to work. I need add a php code from my joomla website but i dont know where i can change the path image folder on this script. i have tried by my self to change rad 33 $files = dirList('.'); to $files = dirList('screenlive2'); but this show only the list and not the image, somebody have any idea? Code: [Select] 1: <html> 2: <head> 3: <style type="text/css"> 4: #files { float: left; font-size: small; } 5: #image { float: right; } 6: .links { float: right; left: -40px; position: relative; } 7: .selected { font-weight: bold; } 8: </style> 9: </head> 10: <body> 11: 12: <?php 13: 14: function dirList ($directory) 15: { 16: $results = array(); 17: $handler = opendir($directory); 18: while ($file = readdir($handler)) { 19: if ($file != '.' && $file != '..') 20: { 21: $suffix = "gif"; 22: 23: if( substr($file, -3) == $suffix ) 24: { 25: $results[] = $file; 26: } 27: } 28: } 29: closedir($handler); 30: return $results; 31: } 32: 33: $files = dirList('.'); 34: 35: arsort($files); 36: 37: //$files = array_reverse( $files ); 38: 39: echo "<div id='files'><ul>"; 40: 41: $prev = ""; 42: $next = ""; 43: $last = ""; 44: 45: foreach( $files as $entry ) 46: { 47: if( isset($_GET['sel']) == false ) 48: { 49: $_GET['sel'] = $entry; 50: } 51: 52: $style = ""; 53: 54: if( $_GET['sel'] == $entry ) 55: { 56: $style="selected"; 57: $selected = $entry; 58: $prev = $last; 59: } 60: 61: echo "<li class='".$style."'><a href='i.php?sel=".$entry."'>"; 62: print_r( $entry ); 63: echo "</a></li>"; 64: 65: if( ($last == $selected) && ($last != "") ) 66: { 67: $next = $entry; 68: } 69: 70: $last = $entry; 71: } 72: 73: echo "</ul></div>"; 74: 75: echo "<div id='image'><img src='".$selected."' alt=''/></div>"; 76: 77: echo "<p class='links'>"; 78: 79: if( $prev != "" ) echo "<a href='i.php?sel=".$prev."'>Up</a>"; 80: echo "<br/>"; 81: if( $next != "" ) echo "<a href='i.php?sel=".$next."'>Down</a>"; 82: 83: echo "</p>"; 84: 85: ?> 86: 87: </body> 88: </html> hello i am adding an image upload script, so users can upload a image with the recipe they are adding, but my script seems to not work, these are the files. add_recipe.php <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!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=ISO-8859-1" /> <meta name="Description" content="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form enctype="multipart/form-data" action="include/recipe.php" method="post"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"></th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="prep" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="cook" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> Choose a picture to upload: <input name="uploaded_file" type="file" /></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> <tr> <td> </td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipe.php (upload form script) <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; mysql_real_escape_string($user); //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); $uploaded_file=$_POST['files']['uploaded_file'] //Сheck that we have a file if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/upload/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } header("Location: ../recipe_added.php"); //} ?> Hey guys!! i'm after a bit of help with a script i am using for simple image upload to server. At the moment the script works fine and will allow upload of JPG files, i want to extend on this to allow GIF and PNG files to be uploaded aswell. This is the script i am using... <?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 600Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 600000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! You can use the following link in the IMS:" .$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 600Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } // $sessionid=session_id() //$newname=$_SESSION['session_name'] header( 'Location: success.php?newname1='.$filename ) ; ?> Any help would be appriciated!! ta!! jonny Hi All Not so much help as here is a handy class for uploading images Please feel free to find security bugs and let me know. Also feel free to use it if you want. http://onlyican.com/test_samples/bl_upload_img.phps To use the class, simply use the following require_once('bl_upload_img.php'); $objUploadImg = new UploadImg(); //Set values here if you wish such as $objUploadImg->setFormField('myFormField'); // The Name from <input type="file" name="myFormField" /> $objUploadImg->setSaveDirMain($_SERVER['DOCUMENT_ROOT'].'/MyImageFolder'; //Make sure to set the permissions //You can change most settings, just look at the function setDetaultValues() to get the function name //Now upload the image if($objUploadImg->uploadImage()){ $strFileName = $objUploadImg->getFileNameMain(); }else{ echo 'Error uploading Image<br />'.$objUploadImg->getErrorMessage(); } If I upload this script in /www/ads/insert/image/ it works fine If I upload it in /www/ads/insert/ it does not work It says PHP could not open /new/ to upload image Code: [Select] <? $target_path = 'images/new/'; $image_name = 'myself.gif'; if( imagejpeg( $tmp_img, "{$target_path}{$image_name}" ) ){ print"image uploaded!"; } ?> I think because PHP only allows to upload images 1 folder deep!!! Why? How do I solve this? I want to create different folders for each group of images Me and a friend are working on a nice secure Image Upload Script. The Upload Class <?php class imageUploader { public $image; // [name], [type], [tmp_name], [error], [size] public $maxFileSize; public $imageExtension; public function __construct($image, $max_file_size) { $this->image = $image; $this->maxFileSize = $max_file_size; } public function isValidImage() { $validExts = array("gif" => "image/gif", "jpeg" => "image/jpeg", "png" => "image/png"); if(in_array(strtolower($this->image["type"]), $validExts) == true) { foreach($validExts as $name => $value) { if(strtolower($this->image["type"]) == $value) { $this->imageExtension = $name; break; } } return true; } else { return false; } } public function isValidSize() { if($this->image["size"] > $this->maxFileSize) { return false; } else { return true; } } public function uploadImage() { if($this->image["error"] > 0) { $errors[] = "An error has occurred"; } elseif($this->isValidImage() == false) { $errors[] = "Invalid file type. Only use JPG, GIF or PNG"; } elseif($this->isValidSize() == false) { $errors[] = "Max file size exceeded."; } if(count((array) $errors) == 0) { move_uploaded_file($this->image["tmp_name"], "Images/" . $this->generateName(rand(10, 15)) . time() . "." . $this->imageExtension); } else { echo implode("<br />", $errors); } } public function createThumbnails() { } public function resizeImage($size_y, $size_x) { } public function generateName($length) { $randstr = ""; for ($i = 0; $i < $length; $i++) { $randnum = mt_rand(0, 61); if ($randnum < 10) { $randstr .= chr($randnum + 48); } elseif ($randnum < 36) { $randstr .= chr($randnum + 55); } else { $randstr .= chr($randnum + 61); } } return $randstr; } } ?> The Everyday HTML Code: [Select] <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>Image</td> <td><input type="file" name="file" id="file" /></td> <td><input type="submit" name="submit" value="Submit" /></td> </tr> </table> </form> My friend did most of the work, but had to go to sleep. My problem is I have a deadline to finish this in under 3 hours for use on my website. What I need it to do is create thumbnails in a /Thumbnail/ sub-folder, with thumbnails being cropped to 100px x 100px. If the full image is larger than 600px x 600px they would have to be resized down to nothing more than 600px for the longest side. I wouldn't mind if they were 300px x 600px, just nothing larger than 600px. I'm willing to pay for this to be completed, I only have roughly $50 though. I know this isn't a freelance area, but it kind of suits this area too with a freelance option. After the upload script is done, I have to work on a php system to get the images and display them, so that I'm not directly linking images. So anyone got some spare time to help out? Hi Im trying to write a script to clean up my image directory which has quite a lot of unused images that have built up over time. In order to do this I am doing the following. First Create a database table called 'image_clean' Then I'm searching through 3 tables and collecting all the image file names and dumping the names in the table 'image_clean' Can do that no problem. So now I have all the images I need in this one table 'image_clean' I now want to go through my directory 'image_uploads' and delete anything thats not in the 'image_clean' table. I know how to delete the files using unlink Im just unsure how to search through the directory file by file and check the file against the database. Im asumming I need to put them in an array. Could anyone give be a clue or two to get me started. I have no problem checking a database against a directory but when its the other way round 'checking a directory against a database I'm lost. What I might do is pop the files to delete in a new database called 'image_delete' so that I can then check the images to delete before I write the unlink script. But I'm just not sure how to pick up each file and compare it to the table. Thanks in advance. ok i have a image uploading script here, it works fine but theres one thing im unhappy with when i first downloaded it it had 1 working one, and the rest examples which you basically have to put together yourself with the sample code (doesen't work without adding missing coding), i have done all that then i took the time to add a random string prefix, im new at php so it took me awhile to work out which strings would work in the right area. now this is what i need help with, when it uploads it has two options, download and remove, these both work fine, but on the file uploader that does work it has "file uploaded to "http://site.com/image.png" the example of course did not work (had loading bar working, and etc but didn't upload or have the feature i just mentioned) and the coder of the script used javascript and inner html for the file uploaded.... etc, because it uploads without refreshing, only thing is i cant seem to get it to work with the new random string i put in, i tried to recreate one with the same type of thing they used for the filename but it didn't work well here is the code, hope you can help. image upload handler Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php $uploader=new PhpUploader(); if(@$_GET["download"]) { $fileguid=$_GET["download"]; $mvcfile=$uploader->GetUploadedFile($fileguid); header("Content-Type: application/oct-stream"); header("Content-Disposition: attachment; filename=\"" . $mvcfile->FileName . "\""); readfile($mvcfile->FilePath); } if(@$_POST["delete"]) { $fileguid=$_POST["delete"]; $mvcfile=$uploader->GetUploadedFile($fileguid); unlink($mvcfile->FilePath); echo("OK"); } if(@$_POST["guidlist"]) { $guidarray=explode("/",$_POST["guidlist"]); //OUTPUT JSON echo("["); $count=0; foreach($guidarray as $fileguid) { $mvcfile=$uploader->GetUploadedFile($fileguid); if(!$mvcfile) continue; //process the file here , move to some where //rename(...) if($count>0) echo(","); echo("{"); echo("FileGuid:'");echo($mvcfile->FileGuid);echo("'"); echo(","); echo("FileSize:'");echo($mvcfile->FileSize);echo("'"); echo(","); echo("FileName:'");echo($mvcfile->FileName);echo("'"); echo("}"); $count++; } echo("]"); } //USER CODE: $rand = substr(md5(microtime()),rand(0,26),10); $targetfilepath= 'savefiles/' . $rand->rand . $mvcfile->FileName; if( is_file ($targetfilepath) ) unlink($targetfilepath); $mvcfile->MoveTo( $targetfilepath ); exit(200); ?> image upload(with form to choose file) Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Ajax - Build attachments table </title> <link href="demo.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var handlerurl='ajax-attachments-handler.php' function CreateAjaxRequest() { var xh; if (window.XMLHttpRequest) xh = new window.XMLHttpRequest(); else xh = new ActiveXObject("Microsoft.XMLHTTP"); xh.open("POST", handlerurl, false, null, null); xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); return xh; } </script> <script type="text/javascript"> var fileArray=[]; function ShowAttachmentsTable() { var table = document.getElementById("filelist"); while(table.firstChild)table.removeChild(table.firstChild); AppendToFileList(fileArray); } function AppendToFileList(list) { var table = document.getElementById("filelist"); for (var i = 0; i < list.length; i++) { var item = list[i]; var row=table.insertRow(-1); row.setAttribute("fileguid",item.FileGuid); row.setAttribute("filename",item.FileName); var td1=row.insertCell(-1); td1.innerHTML="<img src='phpuploader/resources/circle.png' border='0'/>"; var td2=row.insertCell(-1); td2.innerHTML=item.FileName; var td4=row.insertCell(-1); td4.innerHTML="[<a href='"+handlerurl+"?download="+item.FileGuid+"'>download</a>]"; var td4=row.insertCell(-1); td4.innerHTML="[<a href='javascript:void(0)' onclick='Attachment_Remove(this)'>remove</a>]"; } } function Attachment_FindRow(element) { while(true) { if(element.nodeName=="TR") return element; element=element.parentNode; } } function Attachment_Remove(link) { var row=Attachment_FindRow(link); if(!confirm("Are you sure you want to delete '"+row.getAttribute("filename")+"'?")) return; var guid=row.getAttribute("fileguid"); var xh=CreateAjaxRequest(); xh.send("delete=" + guid); var table = document.getElementById("filelist"); table.deleteRow(row.rowIndex); for(var i=0;i<fileArray.length;i++) { if(fileArray[i].FileGuid==guid) { fileArray.splice(i,1); break; } } } function CuteWebUI_AjaxUploader_OnPostback() { var uploader = document.getElementById("myuploader"); var guidlist = uploader.value; var xh=CreateAjaxRequest(); xh.send("guidlist=" + guidlist); //call uploader to clear the client state uploader.reset(); if (xh.status != 200) { alert("http error " + xh.status); setTimeout(function() { document.write(xh.responseText); }, 10); return; } var list = eval(xh.responseText); //get JSON objects fileArray=fileArray.concat(list); AppendToFileList(list); } function ShowFiles() { var msgs=[]; for(var i=0;i<fileArray.length;i++) { msgs.push(fileArray[i].FileName); } alert(msgs.join("\r\n")); } </script> </head> <body> <div class="demo"> <h2>Building attachment table (AJAX)</h2> <p>This sample demonstrates how to build your own attachment table.</p> <?php $uploader=new PhpUploader(); $uploader->MaxSizeKB=10240; $uploader->Name="myuploader"; $uploader->MultipleFilesUpload=true; $uploader->InsertText="Select multiple files (Max 10M)"; $uploader->AllowedFileExtensions="*.jpg,*.png,*.gif,*.bmp,*.txt,*.zip,*.rar"; $uploader->Render(); ?> <br/><br/> <table id="filelist" style='border-collapse: collapse' class='Grid' border='0' cellspacing='0' cellpadding='2'> </table> <br/><br/> <button onclick="ShowFiles()">Show files</button> </div> <script type='text/javascript'> //this is to show the header.. ShowAttachmentsTable(); </script> <script type='text/javascript'> function CuteWebUI_AjaxUploader_OnTaskComplete(task) { var div=document.createElement("DIV"); var link=document.createElement("A"); link.setAttribute("href","savefiles/"+task.rand); link.innerHTML="You have uploaded file : savefiles/"+task.rand; link.target="_blank"; div.appendChild(link); document.body.appendChild(div); } </script> </body> </html> and here is the phpuploader.php file just in case i need help on this one. i am aiming to make my own smaller version of tineye.com or something similar i do have a function that will compare 2 images in GD. all i have to figure out now is how to spider the default image off of major networking sites like facebook,myspace etc. and list all the results found and the similarity of each picture. the function is something like compare_imgs($path,$source_pic,$comparison_pic) { } Hi Guys, I have an issue with the following script which is throwing this error Quote( ! ) Parse error: syntax error, unexpected end of file in C:\wamp64\www\script\images.php on line 41 I just can not see the error, can anyone help (not even sure the script is going to work) <?php /* settings */ //folder for images saving $saveDir = "c:\wamp64\www\script\images\"; //database connection // Turn off all error reporting error_reporting(0); $conn = mysqli_connect('localhost', 'root', '', 'tbl_temp_products'); //start and end table row to prevent timeout or hard server work $start = '1'; $end = '200'; /* end of settings */ //query for fetching the image urls $sql = 'SELECT image_url FROM tbl_temp_products ORDER BY id DESC LIMIT ' . $start . ',' . $end . ''; $res = $conn->query($sql); $count = 0; //this is for count the total row fetched $notify = ''; //this is for seeing result or errors while ($row = $res->fetch_assoc()) { $url = $row(['image_url']); $dest = $saveDir . clean($row(['image_url'])) . '.jpg'; if (!file_exists($dest)){ //prevent file overwriting if (copy($url, $dest)){ $notify.= 'image saved: '. $row(['image_url']); $count++; }else{ $notify.= 'ERROR saving image: '. $row(['image_url']); }else{ $notify.= 'image already exists: '. $row(['image_url']); } } //output result echo 'TOTAL IMAGE SAVED: ' .$count .'\n'; echo $notify; ?> Â I'm new to programming so take it easy on me but I wrote this script for php and it's not complete yet but I could use some advice on file upload security. Besides recreating the image, checking token/request and setting apache settings what else can I do to secure this application. Here's my code:
header('Content-Type: application/json'); $uploaded = array(); if(!empty($_FILES['file']['name'][0])) { $allowedExts = array("gif", "jpeg", "pjpeg", "x-png", "jpg", "png"); foreach ($_FILES['file']['tmp_name'] as $k => $v) { $name = $_FILES['file']['name'][$k]; $type = $_FILES['file']['type'][$k]; $error = $_FILES["file"]["error"][$k]; $size = $_FILES["file"]["size"][$k]; $tempDir = $_FILES["file"]["tmp_name"][$k]; $lowerName = strtolower($name); $temp = explode(".", $lowerName); $extension = end($temp); if ((($type == "image/gif") || ($type == "image/jpeg") || ($type == "image/jpg") || ($type == "image/pjpeg") || ($type == "image/x-png") || ($type == "image/png")) && ($size < 20000) && in_array($extension, $allowedExts)) { if ($error > 0) { echo "Return Code: " . $error . "<br>"; } else { $imageInfo = getimagesize($tempDir); if($imageInfo['mime'] != 'image/gif' && $imageInfo['mime'] != 'image/jpeg' && $imageInfo['mime'] != 'image/jpg' && $imageInfo['mime'] != 'image/pjpeg' && $imageInfo['mime'] != 'image/x-png' && $imageInfo['mime'] != 'image/png') { echo 'Sorry we only accept GIF, JPEG, JPG, PJPEG, X-PNG, PNG image files!'; }else { switch($type) { case 'image/gif': $newName = md5(uniqid()). '.' .time(). '.gif'; break; case 'image/jpeg': $newName = md5(uniqid()). '.' .time(). '.jpeg'; break; case 'image/jpg': $newName = md5(uniqid()). '.' .time(). '.jpg'; break; case 'image/pjpeg': $newName = md5(uniqid()). '.' .time(). '.pjpeg'; break; case 'image/x-png': $newName = md5(uniqid()). '.' .time(). '.x-png'; break; case 'image/png': $newName = md5(uniqid()). '.' .time(). '.png'; break; } if (file_exists('images/' .Session::get(Config::get('session/session_name')). '/' .$newName)) { echo escape($name) . " already exists. "; } else { if(move_uploaded_file($tempDir, 'images/' .Session::get(Config::get('session/session_name')). '/' .$newName)) { $uploaded[] = array( 'name' => $name, 'file' => 'images/' .Session::get(Config::get('session/session_name')). '/' .$newName ); } } } } } else { echo 'Sorry we only accept GIF, JPEG, JPG, PJPEG, X-PNG, PNG image files!'; } } }I've been researching apache Mod_mime but can't find enough info to wrap my mind around it. Edited by Millertime1, 12 August 2014 - 01:00 PM. Hi
Ultimate Aim: To upload multiple images using ajax using a PHP script which will be fired once an image is selected and then return the resulting URL for use in rest of my JS http://peter-gosling...hooseimage.html simple form posts to http://peter-gosling...d/saveimage.php This PHP script below currently gets the posted image and assigns it a random number file name and echos this <?php header("Access-Control-Allow-Origin: *"); $uploaddir = '/home/petergos/public_html/testupload/images/'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); $urlpath = "http://www.peter-gosling.co.uk/testupload/images/"; $temp = explode(".",$_FILES["userfile"]["name"]); $newfilename = rand(1,999999999) . '.' .end($temp); $newuploadfile = $uploaddir . $newfilename; echo "<p>"; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newuploadfile)) { $urlfile = $urlpath . $newfilename; echo $urlfile; } else { echo "Upload failed"; } ?>What I want to do is post my image via ajax but return the value back to my js file I'm not certain on the CORS issue Here's my first attempt http://peter-gosling.com/testupload/ HTML <!DOCTYPE html> <html> <head> </head> <body> <input type="file" accept="image/*;capture=camera" name="taskoutputfile"></input> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $("input[name=taskoutputfile]").on("change", function (){ var fileName = $(this).val(); console.log(fileName); get_image_url(fileName) }); //UPLOAD IMAGE RETURN URL function get_image_url(imageurl) { var dataString = "url="+imageurl; //datastring = $("input[name=sessiontitle]").val(); //AJAX code to submit form. $.ajax({ type: "POST", url: "http://www.peter-gosling.co.uk/testupload/saveimage2.php", data: dataString, cache: false, success: function(html) { alert(html); } }); } </script> </body> </html>PHP <?php header("Access-Control-Allow-Origin: *"); $uploaddir = '/home/petergos/public_html/testupload/images/'; $uploadfile = $uploaddir . basename($_POST['url']); $urlpath = "http://www.peter-gosling.co.uk/testupload/images/"; $temp = explode(".",$_POST['url']); $newfilename = rand(1,999999999) . '.' .end($temp); $newuploadfile = $uploaddir . $newfilename; echo "<p>"; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newuploadfile)) { $urlfile = $urlpath . $newfilename; return $urlfile; } else { echo "Upload failed"; } /* echo "</p>"; echo '<pre>'; echo 'Here is some more debugging info:'; print_r($_FILES); print "</pre>"; */ ?>Have attached all files Any help would be really appreciated Thankyou I had posted a similar post a few days back, about an display script which is supposed to retrieve a stored image from my database and displays it on an html page, but fails to do so. Someone suggested that I upload my image onto a folder on the server and then save the image path name in my database. I found this script(below) which does just that. It uploads the image into a folder on the server called images and stores the image path into a table in my database called images and I know this script works because i saw the file saved in the images folder and the path name inserted into the images table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> Now the display image script accompanying this insert image script is shown below. Code: [Select] <?php // Get our database connector require("config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Dream in code tutorial - List of Images</title> </head> <body> <div> <?php // Grab the data from our people table $sql = "SELECT * from images WHERE image_cartegory = 'main'"; $result = mysql_query($sql) or die ("Could not access DB: " . mysql_error()); while ($row = mysql_fetch_assoc($result)) { echo "<div class=\"picture\">"; echo "<p>"; // Note that we are building our src string using the filename from the database echo "<img src=\"images/ " . $row['filename'] . " \" alt=\"\" />"; echo "</p>"; echo "</div>"; } ?> </div> </body> </html> Well, needless mentioning, the picture isn't displayed. Just a tiny jpeg icon is displayed at the top left hand corner of the page. Figuring out that the problem might be the lack of a header that declares the image type, I add this line header("Content-type: image/jpeg"); but all it does is display a blank white page, without the tiny icon this time. What am I missing? Any clues?? So its a virtual pet script I'm making. This script changes the image of the pet with time. It also puts the user's name,in text on the image. For some reason It doesnt turn out too well= http://amiteka.comli.com/viewpet_forum.php?id=1 Can someone tell me what is wrong with the script or how I can make it show something like; Error on line # <?php require_once('./inc/config.php'); function greaterDate($dformat, $beginDate, $endDate) { $subtract = $endDate - $beginDate; if($subtract > 0) { return 1; } else { return 0; } } function check(){ $pid = mysql_real_escape_string($_GET['id']); $result = mysql_query("SELECT * FROM `pets_adopted` WHERE `id` = '{$pid}'"); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $results = mysql_query("SELECT * FROM `pets_list` WHERE `id` = '{$row [petid]}'"); $pet = mysql_fetch_array($results); $results2 = mysql_query("SELECT * FROM `users` WHERE `id` = '{$row [adopter]}'"); $usercc = mysql_fetch_array($results2); if(greaterDate(".", $row[fulldate], date('Ymd')) > 0) { $im = showpet_forum($pet[adulturl]); $image = imagecreatefrompng($im); return imagepng($image); header('Content-type: image/png'); } elseif(greaterDate(".", $row[halfdate], date('Ymd')) > 0 && greaterDate (".", $row[fulldate], date('Ymd')) <= 0){ $im = showpet_forum($pet[teenurl]); $image = imagecreatefrompng($im); return imagepng($image); header('Content-type: image/png'); } elseif(greaterDate(".", $row[halfdate], date('Ymd')) <= 0){ $im = showpet_forum($pet[babyurl]); $image = imagecreatefrompng($im); return imagepng($image); } } } echo check(); ?> Thank you for any help. I've been creating my own image upload script which takes in several parameters to style an image, however when the function is used new width and new height are specified but I need to use these values to determine cropping coordinates. What I want is when a new width and height is specified, if it is squared i.e. new width is equal to new height AND the original image is not squared i.e. it is a vertical or horizontal rectangle then the central part of that image will be taken. So for example if the user uploads an image 500px high and 100px wide and sets the new width and height both at 100px the new image should be a 100px by 100px square which is taken 200px from the top of the original image. Here is the functions I currently use so far. It's just the coordinates function I can't seem to figure out. Can anyone please help me out:- Code: [Select] //gets the extension of an uploaded file function getExtension($file) { $i = strrpos($file,".");//Gets the position of the "." in the filename if (!$i) { return ""; }//If there is no "." the function ends and returns "" $l = strlen($file) - $i; $ext = substr($file,$i+1,$l); $ext = strtolower($ext); return $ext; } //checks image dimensions and scales both sizes by ratio if it exceeds the max //$w = width, $mw = max width, $h = height, $mh = max height, function checkSize($w, $mw, $h, $mh){ if($w > $mw){//Checks if width is greater than max width $ratio = $mw / $w; $h = $h * $ratio; $h = round($h); $w = $mw; } if($h > $mh){//Checks if height is greater than max height $ratio = $mh / $h; $w = $w * $ratio; $w = round($w); $h = $mh; } return array($w, $h); } //Used to get the coordinates to resize an image by function getCoords(){ } //$f = the file, $ext = file extension, $nw = new width, $nh = new height, $mw = max width, $mh = max height, $nf = new filename, $fo = folder, $des = file size description, $q = quality function imageUpload($f, $ext, $nw, $nh, $mw, $mh, $nf, $fo, $des, $q){ //create image from uploaded file type if($ext=="jpg" || $ext=="jpeg" ){ $src = imagecreatefromjpeg($f); }else if($ext=="png"){ $src = imagecreatefrompng($f); }else{ $src = imagecreatefromgif($f); } //creates a list of the width and height of the image list($w,$h)=getimagesize($f); //sets the coordinates for resizing to 0 by default $dx = $dy = $sx = $sy = 0; //if new width and height are both 0 then a resize is not required so original dimensions need to be validated in case they exceed their max if($nw == 0 && $nh == 0){ if($w > $mw || $h > $mh){//checks if width or height are greater than their max list($w, $h) = checkSize($w, $mw, $h, $mh); } $nw = $w; $nh = $h; }else if($nw == $nh && $w !== $h){//this is for if the resized image needs to be squared but the original image is not a square //COORDS FUNCTION NEEDED HERE } $desext = "";//sets the description extension to "" by default if($des !== 0){//Checks if $des is set or not $desext .= "_".$des;//appends des to $desext ready to be appended to the filename } $foext = "";//sets the folder extension to "" by default if($fo !== 0){//Checks if $fo is set or not $foext .= $fo."/";//appends folder to $foext ready to be appended to the filename } $qv = 100;//sets the quality value to 100 percent by default if($q !== 0){//Checks if $q is set or not $qv .= $q;//sets the quality value to the passed value } $tmp=imagecreatetruecolor($nw,$nh); imagecopyresampled($tmp,$src,$dx,$dy,$sx,$sy,$nw,$nh,$w,$h); $fn = "images/".$foext.$nf.$desext.".jpg";//sets the final filename for upload imagejpeg($tmp,$fn,$qv);//uploads the file //empty variables and clear image imagedestroy($src); imagedestroy($tmp); } Hi guys, I've got an image uploader based on Uploadify, first let me set out what I want the script to do and what it currently does/doesn't do: Upload files of various types into folders named with the Order ID - OK Process the files by checking the file type and acting accordingly - OK Create thumbnails of the images in the /thumbs subdirectory - OK If the file is a PDF, create JPEG images of all pages and subsequent thumbnails - OK If the file is a ZIP, unzip and re-process the contents based on the above rules - FAIL As you can see I'm nearly at the end of my wishlist with this script, currently when it receives a ZIP file is unzip's it correctly placing the contents in the parent (Order-ID) directory however I'm then left with the same situation I have at the very beginning of the script, for example: File in -> "What kind of file are you?" -> Process file based on the answer. What I need to do is: File in -> "What kind of file are you? Oh! a Zip File, let's unzip and ask the same question of the contents!" -> Process contents. So basically I need to ask the same question twice, once of the zip and once of the contents of the unzipped file. This is where I'm struggling, someone told me to use a function which I tried but it kept breaking and I wasn't sure why. Therefore I have attached 2 files. 1 which currently works 99% except for "asking the question again" and one which doesn't work but I was told is the right way to do it File 1: Works 99%. Code: [Select] <?php /* TomBigFile v2.0 Based on Uploadify v2.1.4 Automatic folder creation dependant on order number with a thumbnail subdirectory. All files in are subject to a process which determines their type and acts accordingly. PDF's are automatically converted on the fly to 2 sets of JPEG's and stored accordingly to be accessed by Customer Accounts and Sales Order details area. Revised May 2011 */ // RECEIVE THE DATA FROM THE UPLOAD AND ASSIGN THE VARIABLES if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; // $fileTypes = str_replace('*.','',$_REQUEST['fileext']); // $fileTypes = str_replace(';','|',$fileTypes); // $typesArray = split('\|',$fileTypes); // $fileParts = pathinfo($_FILES['Filedata']['name']); // if (in_array($fileParts['extension'],$typesArray)) { // CREATE THE PARENT DIRECTORY BASED ON ORDER ID AND THE THUMBS SUBDIRECTORY mkdir(str_replace('//','/',$targetPath), 0755, true); mkdir($targetPath . "thumbs", 0755, true); // create thumbs dir move_uploaded_file($tempFile,$targetFile); echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile); // } else { // echo 'Invalid file type.'; // } } // BEGIN CHECKING THE IMAGE LOOKING AT THE FILE TYPE AND ACTING ACCORDINGLY $imgsize = getimagesize($targetFile); switch(strtolower(substr($targetFile, -3))){ case "pdf": $large = substr_replace($targetFile , 'jpg', strrpos($targetFile , '.') +1); $thumbnail = dirname($large).'/thumbs/'.basename(substr($large, 0, -4)."_thumb".strtolower(substr($large, -4))); $cmd = "$targetFile -write $large -thumbnail 64x64 $thumbnail "; exec("convert $cmd "); exit; break; case "jpg": $image = imagecreatefromjpeg($targetFile); break; case "png": $image = imagecreatefrompng($targetFile); break; case "gif": $image = imagecreatefromgif($targetFile); break; case "zip": $zip = new ZipArchive(); $zip->open($targetFile); $zip->extractTo($targetPath); $zip->close(); break; default: exit; break; } $width = 60; //New width of image $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions $src_w = $imgsize[0]; $src_h = $imgsize[1]; $picture = imagecreatetruecolor($width, $height); imagealphablending($picture, false); imagesavealpha($picture, true); $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); // SAVE THE IMAGE(S) if($bool){ switch(strtolower(substr($targetFile, -3))){ case "jpg": //header("Content-Type: image/jpeg"); $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "png": //header("Content-Type: image/png"); imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "gif": //header("Content-Type: image/gif"); imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; } } imagedestroy($picture); imagedestroy($image); echo '1'; // Important so upload will work on OSX ?> File 2: Doesn't work for me but I was told is correct method(s). Code: [Select] <?php /* TomBigFile v2.0 Based on Uploadify v2.1.4 Automatic folder creation dependant on order number with a thumbnail subdirectory. All files in are subject to a process which determines their type and acts accordingly. PDF's are automatically converted on the fly to 2 sets of JPEG's and stored accordingly to be accessed by Customer Accounts and Sales Order details area. Revised May 2011 */ if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; // $fileTypes = str_replace('*.','',$_REQUEST['fileext']); // $fileTypes = str_replace(';','|',$fileTypes); // $typesArray = split('\|',$fileTypes); // $fileParts = pathinfo($_FILES['Filedata']['name']); // if (in_array($fileParts['extension'],$typesArray)) { // Uncomment the following line if you want to make the directory if it doesn't exist mkdir(str_replace('//','/',$targetPath), 0755, true); mkdir($targetPath . "thumbs", 0755, true); // create thumbs dir move_uploaded_file($tempFile,$targetFile); echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile); // } else { // echo 'Invalid file type.'; // } } // start again here after ZIP!!!! function fileScanner($targetFile, $targetPath) { $imgsize = getimagesize($targetFile); $width = 60; //New width of image $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions $src_w = $imgsize[0]; $src_h = $imgsize[1]; $picture = imagecreatetruecolor($width, $height); imagealphablending($picture, false); imagesavealpha($picture, true); $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); if($bool){ switch(strtolower(substr($targetFile, -3))){ case "jpg": //header("Content-Type: image/jpeg"); $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "png": //header("Content-Type: image/png"); imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "gif": //header("Content-Type: image/gif"); imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; } } imagedestroy($picture); imagedestroy($image); } $imgsize = getimagesize($targetFile); switch(strtolower(substr($targetFile, -3))){ case "pdf": $large = substr_replace($targetFile , 'jpg', strrpos($targetFile , '.') +1); $thumbnail = dirname($large).'/thumbs/'.basename(substr($large, 0, -4)."_thumb".strtolower(substr($large, -4))); $cmd = "$targetFile -write $large -thumbnail 64x64 $thumbnail "; exec("convert $cmd "); exit; break; case "jpg": $image = imagecreatefromjpeg($targetFile); break; case "png": $image = imagecreatefrompng($targetFile); break; case "gif": $image = imagecreatefromgif($targetFile); break; case "zip": $zip = new ZipArchive(); $zip->open($targetFile); $zip->extractTo($targetPath); $zip->close(); fileScanner($targetFile, $targetPath); break; default: exit; break; } fileScanner($targetFile, $targetPath); // $width = 60; //New width of image // $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions // // $src_w = $imgsize[0]; // $src_h = $imgsize[1]; // // // $picture = imagecreatetruecolor($width, $height); // imagealphablending($picture, false); // imagesavealpha($picture, true); // $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); // // if($bool){ // switch(strtolower(substr($targetFile, -3))){ // case "jpg": // //header("Content-Type: image/jpeg"); // $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // case "png": // //header("Content-Type: image/png"); // imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // case "gif": // //header("Content-Type: image/gif"); // imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // } // } // // imagedestroy($picture); // imagedestroy($image); echo '1'; // Important so upload will work on OSX ?> If anyone could help me with this I'd greatly appreciate it, I've been reading so many guides on functions and arguments my brain is fried and I fear I've strayed from the subject of what I want to do! Many thanks. Hello, My upload script is working for the most part and while I know that I need a couple of little fixes and will need help with those I also wouldn't mind some tips on how I could have written it better in the first place. The 2 problems I am having. 1. If the copy image fails the script doesn't and still creates a database entry. I would like to stop it from doing that but can't seem to work it out. 2. My mate is getting file type errors even though he is trying to upload small .jpg files. I can't seem to recreate the problem. Maybe someone can see something that might be problematic?? Code: [Select] <? $idir = "../rosysartworks/gallery/"; // Path To Images Directory $tdir = "../rosysartworks/gallery/thumbs/"; // Path To Thumbnails Directory $iwidth = "600"; // Maximum Width For Thumbnail Images $iheight = "600"; // Maximum Height For Thumbnail Images $twidth = "233"; // Maximum Width For Thumbnail Images $theight = "178"; // Maximum Height For Thumbnail Images ?> <? // Catching the inputs $title = Trim(stripslashes($_POST['title'])); $paypal = Trim(stripslashes($_POST['paypal'])); // Check if the form has been submitted. if (isset ($_POST['submit'])) { $problems = FALSE; // No problems so far. // Check for each value. if (empty ($title)) { $problem = TRUE; $problems = 'You forgot to enter a title!<br />'; } if (empty ($paypal)) { $problem = TRUE; $problems = 'You forgot to enter a paypal link!<br />'; } if (!$problem) { // If there are no problems... // Uploading/Resizing Script $url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/JPG") { $file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']); // Move Image From Temporary Location To Permanent Location if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location // Resize for preview image. $simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbanil From $currwidth = imagesx($simg); // Current Image Width $currheight = imagesy($simg); // Current Image Height if ($currwidth > $iwidth && $currheight > $iheight) { $newwidth = $iwidth; $newheight = $newwidth * $currheight / $currwidth; if ($newheight > $iheight) { $newheight = $iheight; $newwidth = $newheight * $currwidth / $currheight; } $dimg = imagecreatetruecolor($newwidth, $newheight); // Make New Image For Preview imagetruecolortopalette($simg, false, 256); // Create New Color Pallete $palsize = ImageColorsTotal($simg); for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image $colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use } imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It) $success = imagejpeg($dimg, "$idir" . $url, 100); // Saving The Image imagedestroy($simg); // Destroying The Temporary Image imagedestroy($dimg); // Destroying The Other Temporary Image if ($success) { print 'Preview image '.$url.' width: '.$newwidth.' height: '.$newheight.' created successfully.<br />'; // Resize successful for preview image unset($success); } } else { unset($simg, $currwidth, $currheight); } // Resize for thumbnail $simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbanil From $currwidth = imagesx($simg); // Current Image Width $currheight = imagesy($simg); // Current Image Height $newwidth = $twidth; $newheight = $newwidth * $currheight / $currwidth; if ($newheight > $theight) { $newheight = $theight; $newwidth = $newheight * $currwidth / $currheight; } // maxWidth: mw, maxHeight: mh, oldHeight: oh, oldWidth: ow, newHeight: nh, newWidth: nw. // nw = mw; nh = nw * oh / ow; // if (nh > mh) { nh = mh; nw = nh * ow / oh } $dimg = imagecreatetruecolor($newwidth, $newheight); // Make New Image For Thumbnail imagetruecolortopalette($simg, false, 256); // Create New Color Pallete $palsize = ImageColorsTotal($simg); for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image $colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use } imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It) $success = imagejpeg($dimg, "$tdir" . $url, 100); // Saving The Image imagedestroy($simg); // Destroying The Temporary Image imagedestroy($dimg); // Destroying The Other Temporary Image if ($success) { print 'Image thumbnail '.$url.' width: '.$newwidth.' height: '.$newheight.' created successfully.'; // Thumbnail created successfully } } else { print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed } // End upload at copy failure } else { print 'Failed to copy image to temp location.'; } } else { print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong print $file_ext; // Show The Invalid File's Extention print '.</font>'; } // End upload script // Define the query. $add_new_session = $sql = "INSERT INTO `gallery` ( `id` , `title` , `image` , `thumb` , `width` , `height` , `paypal` , `date_entered` ) VALUES ( 0, '".mysql_real_escape_string(($title))."', '".mysql_real_escape_string(($url))."', '".mysql_real_escape_string(($url))."', '".mysql_real_escape_string(($newwidth))."', '".mysql_real_escape_string(($newheight))."', '".mysql_real_escape_string(($paypal))."', NOW() )"; // execute the query. if (@mysql_query ($add_new_session)) { print "<p>The new gallery image $url has been added.</p>"; unset($sessionName, $maxAttendees, $newwidth, $newheight); $hidden = 'hidden'; } else{ print '<a name="formTop"></a>'.'<p class="error">Your session has failed to upload. Please contact website support.</p>'; echo $add_new_session; } } else { // Forgot a field. // print '<p>Please try again!</p>'; $problems .= '<a name="formTop"></a>'.'Please try again!<br />'; if ($problem) { print '<p class="error">' . $problems . '</p>'; } } // End of handle form IF // Display the form print '<h2>Upload New Image</h2>' . '<p>Please only try uploading .jpg images</p>' . '<form method="post" action="index.php" enctype="multipart/form-data">' . '<label>Title:</label>' . '<input type="text" name="title" class="form">' . '<br />' . '<label>Image:</label>' . '<input type="file" name="imagefile" class="form">' . '<br />' . '<label>Paypal Link:</label>' . '<input type="text" name="paypal" class="form" size="50">' . '<br /><br />' . '<input name="submit" type="submit" value="Sumbit" class="form">' . '<input type="reset" value="Clear" class="form">' . '</form>'; ?> |