PHP - Advice On Image Upload Script.
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. Similar TutorialsHey 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 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"); //} ?> 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(); } 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
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 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. Hi all! I have a problem with an image uploading script and at the moment it keeps the image name the same, obviously people don't have very adventurous names for their images "image1" and they are over writing each other. How do I put a random 5 digit number on the end to make them all unique? Thanks. Code: [Select] $image1 = mysql_real_escape_string("$idir" . $_FILES['fupload2']['name']); $image2 = mysql_real_escape_string("$idir" . $_FILES['fupload3']['name']); $image3 = mysql_real_escape_string("$idir" . $_FILES['fupload4']['name']); $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], "$idir" . $_FILES['fupload']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload2'])){ //upload the image to tmp directory $url = $_FILES['fupload2']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload2']['type'] == "image/jpg" || $_FILES['fupload2']['type'] == "image/jpeg" || $_FILES['fupload2']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload2']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload2']['tmp_name'], "$idir" . $_FILES['fupload2']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload3'])){ //upload the image to tmp directory $url = $_FILES['fupload3']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload3']['type'] == "image/jpg" || $_FILES['fupload3']['type'] == "image/jpeg" || $_FILES['fupload3']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload3']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload3']['tmp_name'], "$idir" . $_FILES['fupload3']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload4'])){ //upload the image to tmp directory $url = $_FILES['fupload4']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload4']['type'] == "image/jpg" || $_FILES['fupload4']['type'] == "image/jpeg" || $_FILES['fupload4']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload4']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload4']['tmp_name'], "$idir" . $_FILES['fupload4']['name']); // Move Image From Temporary Location To Permanent Location } } 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>'; ?> Hi all I have a script that takes up to 3 images and resizes them. It works except for if you try and upload images over roughly 500kb. I then get the message: Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y bytes) Here's a snippet of the code for one image: Code: [Select] // Process image 1 : if(!empty($_FILES['image1']['name'])) { $imagelarge = $_FILES['image1']['tmp_name']; $imagelargemain = $_FILES['image1']['name']; $pathInfo = pathinfo($imagelargemain); $rand = rand(1, 100000000000000); $name = $rand . '.' . $pathInfo['extension']; $src = imagecreatefromjpeg($imagelarge); list($width,$height)=getimagesize($imagelarge); if ($width > $height) { $newwidth=600; $newheight=($height/$width)*$newwidth; } elseif ($height > $width) { $newheight=400; $newwidth=($width/$height)*$newheight; } $center_x = (600/2)-($newwidth/2); $center_y = (400/2)-($newheight/2); $tmp=imagecreatetruecolor(600,400); $white = imagecolorallocate($tmp, 255, 255, 255); imagefill($tmp, 0, 0, $white); imagecopyresampled($tmp,$src,$center_x,$center_y,0,0,$newwidth,$newheight,$width,$height); $filename = WEB_UPLOAD."images/adverts/". $name; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); $image_sql = mysql_query("UPDATE `adverts` SET image1 ='".$name."' WHERE id='".$insertid."'") or die ("Error updating database"); } Any ideas why this happens? Many thanks Pete Hi all, been a while since I've been on here.
I am in the process of designing a site similar to dating sites like plenty of fish, or ok cupid. The only spot I am running into trouble is with images.
If you are familiar with either of these sites, you will understand what I am looking for.
Basically, a user is able to upload one or more images via an uploader (Not sure if it's ajax or flash to be honest, but I would like to stick to PHP/Ajax).
While uploading, they have the ability to crop their images to specific sizes set by the site - for example, the image must be cropped to fit a 400 px X 400 px area, so they have the ability to decide which part of a larger image is saved rather than just have the system crop it and perhaps not show what was intended.
After they finish and click upload, the image is saved to the server, as well as a thumbnail, which, without a refresh, is then added to their page along with their previous images if there were any. From that point, they have the option to delete images they don't like, set the main image for their profile and edit/add captions to the images, again, all without refreshing the page.
Would anyone happen to know of a script I could start with and change to suit my needs, but that would pretty much allow this kind of image uploading/manipulation? I've done google searches for hours now and have looked at a ton of scripts but not a single one I have found seems to be able to do any of these things. Most just have multiple file uploads with cropping ability, but not by the users themselves, just a predetermined dimension.
Any help pointing me in the right direction would be greatly appreciated.
Jax
Hi I have an image uploading script that won't upload images... It worked at one point when i had folder permission at 0777 but i was told that is risky so i changed it to 0775 Now it won't work and i can't use 0777. Any one know what i need to do to get it to work? This is my script: Code: [Select] <?php $salt = 35322232414; $name = $salt.$safe; $name = md5($name); if(isset($_POST['submit'])){ if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 1000000)) { if ($_FILES["file"]["error"] > 0) { echo $_FILES["file"]["error"]; } else { $filename = md5(serverdate()) . $_FILES["file"]["name"]; if (file_exists("userimages/".$name."/".$filename)) { echo "Image already uploaded!"; } else { if (is_dir("userimages/".$name) == FALSE){ mkdir("userimages/".$name, 0775); //permissions } move_uploaded_file($_FILES["file"]["tmp_name"], "userimages/".$name."/" . $filename); echo "Image has been uploaded!"; } Error i get: Quote Warning: move_uploaded_file(images/73640de25b7d656733ce2f808a330f18/7fc9cb9cf5ae1f7a5dd9105d3f9559fb_63.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in uploadfile.php on line 41 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpjrX3SO' to 'images/73640de25b7d656733ce2f808a330f18/7fc9cb9cf5ae1f7a5dd9105d3f9559fb_63.jpg' in uploadfile.php on line 4 Hi all, As you will see this is my first post in I really hope somebody can nail this for me, as I have been working on this for some time and I cannot get it to work. Basically this is the final part of a CMS I'm building, and all was fine until I needed to build in an option of a multiple image uploader to accompany all other stock details. I have managed to nail the 'insert' part of the multiple image uploader in this case up to 4 images, and the code is below for this part, any help with improvements though will be greatly appreciated. Code: [Select] if(isset($_POST['btnsubmit'])) { $flag=$_POST['flag']; if ($flag==0) { $name=$_POST['txtname']; $desc1=$_POST['e1m1']; $meta=$_POST['txtmeta']; $sr=$_POST['srno1']; $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $str_str=''; $p=''; $j=0; for($i=0;$i<=3;$i++){ $j++; $p=$_REQUEST['p$j']; $file=$_FILES['pic']['name'][$i]; if(!empty($file) ){ $str_str.=",pic$j='$file'"; } else if(!empty($p))$str_str.=",pic$j='$p'"; $path1="imgdata/stock/".$file; copy($_FILES['pic']['tmp_name'][$i], $path1); } $q24=mysql_query("update stock set stock_Name='$name', stock_MetaTitle='$meta', parent_Category='$pcats', sub_Category='$subcats', stock_Image='imgdata/stock/$pic[0]', stock_Image2='imgdata/stock/$pic[1]', stock_Image3='imgdata/stock/$pic[2]', stock_Image4='imgdata/stock/$pic[3]', stock_Ref='$ref', stock_Description='$desc1', stock_Maker='$maker', stock_Date='$date', stock_Weight='$weight', stock_Height='$height', stock_Depth='$depth',stock_Width='$width', stock_Price='$price', stock_Sold='$sold', stock_Active='$active', stock_DateTime='$dt2' where stock_Id=$sr") or die (mysql_error()); $flag=1; $conf="Data Updated Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_categories.php'>here</a> to continue"; $update="1"; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <input type="submit" name="btnsubmit" value="Submit"> <input type="submit" name="btndelete" value="Delete" DEFANGED_OnClick="return check();"> <input type="hidden" name="srno1" value="<?= $rows["stock_Id"];?>"> <input type="hidden" name="action" value="Upload"> All seems to be fine above, I can upload 1,2,3 or 4 images and the image goes into the server and the path to the database. But I then needed the option for my client to be able to click to edit a certain stock and then aswel as edit the other details, if he wanted to change one pic, no pics or all 4 he could and when he clicked submit, if there was a new image it would change if not it would stay as it is. So here is my attempt and at the moment it doesnt work, so I'm looking for help of any kid and anything can change. Code: [Select] $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $meta=$_POST['txtmeta']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $pic1=''; for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$pic1[$i]=$_FILES['pic1']['name'][$i]; else $pic1[$i]=''; } for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$path1= "./imgdata/stock/".$_FILES['pic1']['name'][$i]; //echo $_FILES['pic1']['tmp_name'][$i]." :". $path1; if(!empty($_FILES['pic1']['name'][$i])&&isset($_FILES['pic1']['name'][$i]))copy($_FILES['pic1']['tmp_name'][$i], $path1); } $q=mysql_query("insert into stock (stock_Name, stock_MetaTitle, parent_Category, sub_Category, stock_Ref, stock_Description, stock_Maker, stock_Date, stock_Weight, stock_Height, stock_Depth, stock_Width, stock_Price, stock_Sold, stock_Image, stock_Image2, stock_Image3, stock_Image4, stock_Active, stock_DateTime) values('$name','$meta','$pcats','$subcats','$ref','$desc','$maker','$date','$weight','$height','$depth','$width','$price','$sold','imgdata/stock/$pic1[0]','imgdata/stock/$pic1[1]','imgdata/stock/$pic1[2]','imgdata/stock/$pic1[3]','$active','$dt2')") or die (mysql_error()); $conf="Data Inserted Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_stock.php'>here</a> to continue"; $update=1; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p1" value="<?php echo $pic1;?>" /> <img src="<?php echo $pic1;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p2" value="<?php echo $pic2;?>" /> <img src="<?php echo $pic2;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p3" value="<?php echo $pic3;?>" /> <img src="<?php echo $pic3;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p4" value="<?php echo $pic4;?>" /> <img src="<?php echo $pic4;?>" height="100px" /> </td> </tr> What happens above as its all on the same page, is when a stock item is selected to be edited the form to update the images changes to the image upload options above, instead of the original ones for a new stock item at the top of this post. I can provide anything you need to help me with this, so please can somebody take a look and see if it can be got working, as its been a long problem for me this. Cheers The Script:
<?php if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; for ($i = 0; $i < count($_FILES['file']['name']); $i++) { $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); } // To create the thumbnails. function make_thumb($src, $dest, $desired_width) { /* read the source image */ $source_image = imagecreatefromjpeg($src); $width = imagesx($source_image); $height = imagesy($source_image); /* find the "desired height" of this thumbnail, relative to the desired width */ $desired_height = floor($height * ($desired_width / $width)); /* create a new, "virtual" image */ $virtual_image = imagecreatetruecolor($desired_width, $desired_height); /* copy source image at a resized size */ imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image, $dest); } $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/"; $desired_width = 100; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } } ?>With this: $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/";I get this error message: Warning: imagejpeg(C:/xampp/htdocs/gallerysite/multiple_image_upload/thumbs/): failed to open stream: No such file or directory in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 49With this: $dest = "http://localhost/gallerysite/multiple_image_upload/thumbs/";I get this error message: Warning: imagejpeg(http://localhost/gallerysite/multiple_image_upload/thumbs/): failed to open stream: HTTP wrapper does not support writeable connections in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 49When I try deleting the "thumbs" folder and then try to upload an image, then I get this error message: Warning: imagejpeg(C:/xampp/htdocs/gallerysite/multiple_image_upload/thumbs/): failed to open stream: Invalid argument in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 49The spot of line 49 is this, at the spot where the script creates the thumbnails: /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image, $dest); }Also, with this part right here I am not getting an error message, which means that this part works fine in comparison: $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded imagesThe script itself works fine. The script also uses javascript for multiple image upload. I am using XAMPP. The folder "thumbs" is set to "read-only", when I try to uncheck the "read-only" option in the properties in Windows then it sets itself back again to "read-only". Then again, the script works fine when it comes to the "uploads" folder. This is mentioned in comparison to the "thumbs" folder. Any suggestions on how to solve this? EDIT: I am using XAMPP. The folder "thumbs" is set to "read-only", when I try to uncheck the "read-only" option in the properties in Windows then it sets itself back again to "read-only". I am wondering if I would have issue that the option sets itself back again with Linux? Edited by glassfish, 11 October 2014 - 05:35 PM. So this script did work in previous versions oh php but in php5 I get the error, "Sorry, uploaded images must be of type jpg or jpeg, (not )." So it looks like it's not recognizing my file as a jpeg?? Any contributions towards a fix are GREATLY appreciated!!! If there are clean, nice (EASY) php5 scripts available for this simple image uploading and thumbnail creation I would consider starting this over. //Listing page code: echo "<form name=\"addCat\" enctype=\"multipart/form-data\" action=\"preview.php\" method=\"post\">"; <INPUT type="file" name="pic1" size="50" value=""> <INPUT type="file" name="pic2" size="50" value=""> <INPUT type="file" name="pic3" size="50" value=""> <INPUT type="file" name="pic4" size="50" value=""> <input type="submit" value="Upload Images"> //preview.php page code: $pic1 = $_FILES['pic1']; $pic2 = $_FILES['pic2']; $pic3 = $_FILES['pic3']; $pic4 = $_FILES['pic4']; function ResizeImage($im,$maxwidth,$maxheight,$name){ $width = imagesx($im); $height = imagesy($im); if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ if($maxwidth && $width > $maxwidth){ $widthratio = $maxwidth/$width; $RESIZEWIDTH=true; } if($maxheight && $height > $maxheight){ $heightratio = $maxheight/$height; $RESIZEHEIGHT=true; } if($RESIZEWIDTH && $RESIZEHEIGHT){ if($widthratio < $heightratio){ $ratio = $widthratio; }else{ $ratio = $heightratio; } }elseif($RESIZEWIDTH){ $ratio = $widthratio; }elseif($RESIZEHEIGHT){ $ratio = $heightratio; } $newwidth = $width * $ratio; $newheight = $height * $ratio; if(function_exists("imagecopyresampled")){ $newim = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); }else{ $newim = imagecreate($newwidth, $newheight); imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); } ImageJpeg (($newim),$name . ".jpg"); ImageDestroy ($newim); }else{ ImageJpeg ($im,$name . ".jpg"); } } // Set up some variables flush(); set_time_limit(210); // set process page limit to 3.5 minutes $maxfilesize = "102400"; //# individual file size limit - in bytes (102400 bytes = 100KB) $path="2012images"; $thumbpath="thumbs"; // two data pulls to rename images - would be easier to have a permanent counter...fix later $mysql[getpicname] = mysql_query("select pic from picname"); $z = mysql_fetch_array($mysql[getpicname]); $new_filename=$z[pic]; $new_z[pic]=$z[pic]+$total_pics; if(@mysql_query("UPDATE picname SET pic = '$new_z[pic]' ")) echo ""; // Create thumbnail from imgurl and store in thumbs // Height to reszie image to (in pixels) $RESIZEHEIGHT=200; // Width to reszie image to (in pixels) $RESIZEWIDTH=200; //thumbnail to thumbs folder, named same as 1st image $FILENAME=$thumbpath."/".$new_filename; $thumb_name=$thumbpath."/".$new_filename.".jpg"; // create a thumbnail from the first image only $im = imagecreatefromjpeg($_FILES['pic1']['tmp_name']); if($im) { if(file_exists("$pic_1.jpg")) { unlink("$pic_1.jpg"); } if (ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME)) ImageDestroy ($im); } //now upload the images..... for ($i=1;$i<5;$i++) { //check if blank or image $xpic="pic".$i; if (($$xpic<>"none") and ($$xpic<>"")) { // check if jpg $cert1 = "image/pjpeg"; //jpg $cert2 = "image/jpeg"; //jpg (for MAC) $xtype =$HTTP_POST_FILES[$xpic]['type']; $xsize =$HTTP_POST_FILES[$xpic]['size']; if (($xtype <> $cert1) AND ($xtype <> $cert2)) { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Missing or Invalid Information</DIV><br>"; echo "<DIV class=\"requiredtext\">Sorry, uploaded images must be of type jpg or jpeg, (not $xtype).</DIV><BR>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } if ($xsize > $maxfilesize) { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Missing or Invalid Information</DIV><br>"; echo "<DIV class=\"requiredtext\">Sorry, uploaded images must be under the maximum size requirements.</DIV><BR>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } else { // upload to server $dest=$path."/".$new_filename.".jpg"; If (move_uploaded_file($$xpic, $dest)) { $photo[$i]=$dest; $new_filename+=1; } else { echo "<DIV class=\"errorsubheading\"><br><br>Alert - Upload Failed!</DIV><br>"; echo "<BR><br><br>"; include ("footer.php"); exit(); } // upload sucessful } // end type check } // end check if blank } so what i have going on is that i need help writing a basic script to upload original and copy with resize for thumbnail. then also need to rename both image files with content in the form. My server supports GD Library and that imagemagik or whatever it is lol. upload dirs orig: ../media/photos/ thumb: ../media/photos/thumb/ mySQL DB: name: m_photos fields: id(INT) m_cat(varchar) m_sub_cat(varchar) pic(varchar) description(varchar) p_group(varchar) I have the form written up for how it should look like: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> Upload an image for processing<br /> <input type="file" name="Image"><br /> <select name="sub_group"> <option value="Photo Shoot">Photo Shoot</option> <option value="Live Performances">Live Performances</option> <option value="Randoms">Randoms</option> <option value="Fan Photos">Fan Photos</option> </select><br /> Location: <input type="text" name="p_group" /><br /> Date of Pic: <input type="text" name="date" /><br /> Description: <input type="text" name="description" /><br /> <input type="submit" value="Upload"> </form> so what needs to happen is for the file upload name. it needs to grab a count from "p_group" database to give it a starting number in a "00" pattern and then the date of pic needs to go in there next then the p_group name. so when the files gets uploaded it would look something like this after upload. "03 - Oct 21, 2011 - The Mex.jpg" NOTE: all pics must be converted to ".jpg" extension. both the orig and thumb will use that same file name cuz they just go into different dirs re-sizing for the thumbnail should be done by aspect ratio and needs to either be 300px width or 400px height. so if anyone would like to help me out please do. im not the greatest at writing in php yet Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks This is my first PHP script. Its a login script if you have time to read through the whole thing that would be great if not then advice on any obvious things would be great. few side notes. - not on a real server so the sql connect info is default. - on loginchk.php i will eventually write something to block someone if a lot of continuous failed logins from same ip. - let me know if you happen to see anything that is slowing it down. Hi, I'm pretty new to PHP, struggled my way through most of my encounters with PHP so far, but getting the hang of it I'm looking for a simple script that turns a number or word served by a weather station into a graphic. E.g. If the temp is 20 degrees, a graphic I've designed would be shown, or a cloud or the sun or whatever. At the moment the weather station feed is converted from 'webtags' in to php tags (temp is $temp, wind is $wind etc.) and these echo out as numbers and words on the website. I can sort of see how it would work in my head, but need a little help. Can anyone please point me in the right direction? Thanks (for reference site is www.southtyneweather.co.uk) |