PHP - How Can I Edit Just One Image At On Time With A Multiple Image Upload Form?
How can i edit just one image at on time with a multiple image upload form? I have the images being stored in a folder and the path being stored in MySQL. I also have the files being uploaded with a unique id. My issue is that I want to be able to pass the values of what is already in $name2 $name3 $name4 if I only want to edit $name1. I don't want to have to manually update the 4 images. Here is the PHP:
Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $uploadDir = 'upload/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if ($fileName != ""){ $filePath = $uploadDir; $fileName = str_replace(" ", "_", $fileName); //Split the name into the base name and extension $pathInfo = pathinfo($fileName); $fileName_base = $pathInfo['fileName']; $fileName_ext = $pathInfo['extension']; //now we re-assemble the file name, sticking the output of uniqid into it //and keep doing this in a loop until we generate a name that //does not already exist (most likely we will get that first try) do { $fileName = $fileName_base . uniqid() . '.' . $fileName_ext; } while (file_exists($filePath.$fileName)); $file_names [] = $fileName; $result = move_uploaded_file($tmpName, $filePath.$fileName); } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[] = $filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i = 0; $i < 4; $i++) { $values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : ''; if($values[$i] != '') { $updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); Similar TutorialsI am VERY new to PHP, but I am trying to adapt code from http://www.4wordsystems.com/php_image_resize.php to work with multiple images. Can any please help? I know I need to place it in a loop of some kind, but I don't know how to write the code for that. Here is the code: HTML FORM CODE: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data" > <input type="file" name="uploadfile"/> <input type="submit"/> </form> upload.php CODE: Code: [Select] <?php // This is the temporary file created by PHP $uploadedfile = $_FILES['uploadfile']['tmp_name']; // Create an Image from it so we can do the resize $src = imagecreatefromjpeg($uploadedfile); // Capture the original size of the uploaded image list($width,$height)=getimagesize($uploadedfile); // For our purposes, I have resized the image to be // 600 pixels wide, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max width other than // 600, simply change the $newwidth variable $newwidth=600; $newheight=($height/$width)*600; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); // For our purposes, I have resized the image to be // 150 pixels high, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max height other than // 150, simply change the $newheight variable $newheight=150; $newwidth=($width/$height)*150; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/thumb_". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request // has completed. echo "Successfully Uploaded: <img src='".$filename."'>"; ?> Hello,
I'm developing one website for a real-estate agency. I have a html form that is used to submit property details, There is multiple form inputs and also I need to upload multiple property images using Dropzone JS multiple image upload. Here I'm validating form inputs using jQuery Validation library. Validation works perfect and data Is being to posted to php file called submit_property_data.php. But when I implement the Dropzone JS image upload its not working.
JS File (property-submit.js)
$('document').ready(function() { $("#notification-property").hide(); /* handling form validation */ $("#property-form").validate({ rules: { prop_title: "required", prop_price: { required: true, digits: true }, prop_area: { required: true, digits: true }, prop_address: "required", prop_message: { required: true, minlength: 10, maxlength: 2000 }, prop_owner_name: "required", prop_owner_email: { required: true, email: true }, prop_owner_phone: { required: true, digits: true }, }, messages: { 'prop_title': { required: "Please enter title for your property" }, prop_price: { required: "Please enter price of your property", digits: "Please enter price in digits (AED)" }, prop_area: "Please enter Sqft of your property", prop_address: "Please enter address of your property", prop_message: { required: "Please enter detailed Information", minlength: "Please enter something about your property in 50 - 20000 characters", maxlength: "Please enter something about your property in 50 - 20000 characters" }, prop_owner_name: "Please enter your name", prop_owner_email: { required: "Please enter your email address", email: "Please enter valid email address" }, prop_owner_phone: { required: "Please enter your phone number", digits: "Please enter valid phone number" }, }, submitHandler: submitPropertyForm }); /* Handling login functionality */ function submitPropertyForm() { var data = $("#property-form").serialize(); $.ajax({ type: 'POST', url: 'submit_property_data.php', data: data, beforeSend: function() { $("#submit-button").html('<span class="glyphicon glyphicon-transfer"></span> Submiting ...'); }, success: function(response) { if (response == "ok") { console.log(1); document.getElementById("property-form").reset(); $("#notification-property").html('<b> ' + response + ' !</b>').show(); //setTimeout(' window.location.href = "dashboard.php"; ',4000); } else { $("#notification-property").fadeIn(1000, function() { $("#notification-property").html('<b>' + response + ' !</b>').fadeOut(); $("#submit-button").html(' Send'); }); } }, complete:function(){ $('body, html').animate({scrollTop:$('form').offset().top}, 'slow'); } }); return false; } $("#submit-button").bind('click', function() { if ( $("#property-form").valid() ) { submitPropertyForm(); } else { console.log('form invalid'); } }) Dropzone.autoDiscover = false; $(function () { $("div#myDropzone").dropzone({ url: 'submit_property_data.php', addRemoveLinks: true, maxFiles:11, uploadMultiple: true, autoProcessQueue: false, parallelUploads: 10, init: function () { var myDropzone = this; // Update selector to match your button $("#submit-button").click(function (e) { e.preventDefault(); myDropzone.processQueue(); }); this.on('sending', function(file, xhr, formData) { // Append all form inputs to the formData Dropzone will POST var data = $('#property-form').serializeArray(); $.each(data, function(key, el) { formData.append(el.name, el.value); }); }); this.on("success", function(file, responseText) { alert(responseText); }); }, }); }); });
HTML File (submit-property.php)
<html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script> !-- Submit Property start --> <div class="content-area-7 submit-property"> <div class="container"> <div class="row"> <div class="col-md-12"> <!-- <div id="error_message" class="notification-box"></div> --> </div> <div id="notification-property" class="notification-box">sd</div> <div class="col-md-12"> <div class="submit-address"> <form name = "property-form" method="post" id="property-form"> <div class="main-title-2"> <h1><span>Tell Me</span> Something About Your Property</h1> </div> <div class="search-contents-sidebar mb-30"> <div class="form-group"> <label>Property Title</label> <input class="input-text" name="prop_title" id="prop_title" placeholder="Property Title"> </div> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Status</label> <select class="selectpicker search-fields" id="prop_status" name="prop_status"> <option value="Sale">For Sale</option> <option value="Rent">For Rent</option> </select> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Type</label> <select class="selectpicker search-fields" id="prop_title" name="prop_type"> <option value="Modern">Modern</option> <option value="Traditional">Traditional</option> <option value="Arabic">Arabic</option> </select> </div> </div> </div> <div class="row"> <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Price (Dirham)</label> <input class="input-text" name="prop_price" id="prop_price" placeholder="AED"> </div> </div> <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Sqft</label> <input class="input-text" name="prop_area" id="prop_area" placeholder="SqFt"> </div> </div> <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Bed Rooms</label> <select class="selectpicker search-fields" name="prop_rooms" id="prop_rooms"> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> <!-- <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Bathroom</label> <select class="selectpicker search-fields" name="1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> --> </div> </div> <div class="main-title-2"> <h1><span>Location</span></h1> </div> <div class="row mb-30 "> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Address</label> <input class="input-text" id="prop_address" name="prop_address" placeholder="Address"> </div> </div> </div> <div class="main-title-2"> <h1><span>Upload</span> Photos Of Villa </h1> </div> <div id="myDropzone" class="dropzone dropzone-design mb-10"> <div class="dz-default dz-message" data=""><span>Drop files here to upload</span></div> </div> <div class="main-title-2"> <h1><span>Detailed</span> Information</h1> </div> <div class="row mb-30"> <div class="col-md-12"> <div class="form-group"> <textarea class="input-text" id="prop_message" name="prop_message" placeholder="Detailed Information"></textarea> </div> </div> </div> <!--<div class="row mb-30"> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Building Age <span>(optional)</span></label> <select class="selectpicker search-fields" name="years"> <option>0-1 Years</option> <option>0-5 Years</option> <option>0-10 Years</option> <option>0-20 Years</option> <option>0-40 Years</option> <option>40+Years</option> </select> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Bedrooms (optional)</label> <select class="selectpicker search-fields" name="1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Bathrooms (optional)</label> <select class="selectpicker search-fields" name="1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="col-lg-12"> <label class="margin-t-10">Features (optional)</label> <div class="row"> <div class="col-lg-4 col-sm-4 col-xs-12"> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_parking" name="opt_parking" value="1" type="checkbox"> <label for="checkbox1"> Free Parking </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_air_condition" name="opt_air_condition" value="1" type="checkbox"> <label for="checkbox2"> Air Condition </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_seat" name="opt_seat" value="1" type="checkbox"> <label for="checkbox3"> Places to seat </label> </div> </div> <div class="col-lg-4 col-sm-4 col-xs-12"> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_swimming" name="opt_swimming" value="1" type="checkbox"> <label for="checkbox4"> Swimming Pool </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_laundary" name="opt_laundary" value="1" type="checkbox"> <label for="checkbox5"> Laundry Room </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_window_covering" name="opt_window_covering" value="1" type="checkbox"> <label for="checkbox6"> Window Covering </label> </div> </div> <div class="col-lg-4 col-sm-4 col-xs-12"> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_parking" name="opt_parking" value="1" type="checkbox"> <label for="checkbox7"> Central Heating </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="checkbox8" type="checkbox"> <label for="checkbox8"> Alarm </label> </div> </div> </div> </div> </div>--> <div class="main-title-2"> <h1><span>Contact</span> Details</h1> </div> <div class="row"> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Name</label> <input class="input-text" name="prop_owner_name" id="prop_owner_name" placeholder="Name"> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Email</label> <input class="input-text" name="prop_owner_email" id="prop_owner_email" placeholder="Email"> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Contact No</label> <input class="input-text" name="prop_owner_phone" id="prop_owner_phone" placeholder="Phone"> </div> </div> </div> <div class="col-md-12"> <button type="button" name="submit-button" id="submit-button">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> <script src="property-submit.js"></script> <script src="js/dropzone.js"></script> </html>
PHP File (submit_property_data.php)
<?php echo "ok"; require_once("functions.php"); $ds = DIRECTORY_SEPARATOR; //1 $storeFolder = 'villas-images'; $encpt_data = rand(1000,5000); if (!empty($_FILES)) { $tempFile = $_FILES['file']['tmp_name']; //3 $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4 $targetFile = $targetPath.$_FILES['file']['name']; //5 if(move_uploaded_file($tempFile,$targetFile)) { echo '<b>Success</b>'; } } ?>
What I actually need ?
I need to validate the form inputs first & upload the images once the form is valid also I need to post all the inputs to my php file called submit_property_data.php Also I need the image inputs to store into my database.
I need code for upload images for php as well as to edit that image
I have a working image upload script that uploads, renames the file and adds filename to the database. is it possible to include some sort of image resize code? if so can anyone point me in the right direction or better still show some example code and explain how it works etc. below is my working code: Code: [Select] <?php $rand = mt_rand(1,9999999); $member_id = $_SESSION['SESS_MEMBER_ID']; $caption = $_POST["caption"]; if(isset($_FILES['uploaded']['name'])) { $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $errors = array(); $target = "gallery/"; $fileBaseName = substr($fileName, 0, strripos($fileName, '.')); // Get the extension from the filename. $ext = substr($fileName, strpos($fileName,'.'), strlen($fileName)-1); //$newFileName = md5($fileBaseName) . $ext; $newFileName = $target . $rand . "_" . $member_id.$ext; // Check if filename already exists if(file_exists("gallery/" . $newFileName)) { $errors[] = "The file you attempted to upload already exists, please try again."; } // Check if the filetype is allowed. if(!in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(!filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(!is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $newFileName)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //Lets INSERT database information here if(count($errors)==0) { $result = mysql_query("INSERT INTO `gallery` (`image`, `memberid`, `caption`) VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Image has been uploaded.<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br /><br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file:<br /><input class='text' name='uploaded' type='file' /><br />\n"; echo "Image Caption:<br /><input class='text' name='caption' type='text' value='' /><br /><br />\n"; echo "<input class='Button' type='submit' value='Upload' />\n"; echo "</form>\n"; } ?> Many thanks to phpfreaks again. <form id="test" action="<?php $_POST['SERVER_SELF'] ?>" method="POST" enctype="multipart/form-data" > <div class="wrap"> <p>upload image here for Contact Page</p> <input type="file" name="image"> <br> <input name="about1" type="submit" value="Upload image"> <br> </div> </form> <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100000"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['about'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=contactbg.'.'.jpg; //the new name will be containing the full path where will be stored (images folder) $newname="C:/xampp/htdocs/Dirk-taat/wp-content/themes/dirktaat/images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['about']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['about1'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=aboutme_bg.'.'.png; //the new name will be containing the full path where will be stored (images folder) $newname="C:/../.../../.../../.../images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['about1']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } } ?> the above code works only for 1 upload box if more than one upload box it does not upload the file. Thanks i have done a coding for image multiple upload , the coding is working perfectly when i store image in the image folder but when trying to insert the image name in database its not working. important thing is while we store the value of images it should store in single column seperated with comma or special character. like this id image 1 car.jpg,bike.jpg,sun.jpg pls help to me, thanks in advance. Here is the code. img.php <?php $max_no_img=5; // Maximum number of images value to be set here echo "<form method=post action=addimgck.php enctype='multipart/form-data'>"; echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>"; for($i=1; $i<=$max_no_img; $i++){ echo "<tr><td>Images $i</td><td> <input type=file name='images[]' class='bginput'></td></tr>"; } echo "<tr><td colspan=2 align=center><input type=hidden name='userid' value='68'></td></tr>"; echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>"; echo "</form> </table>"; ?> addimgck.php <?php ini_set('display_errors', 1); ini_set('error_reporting', E_ALL); function findexts ($filename) { $filename = strtolower('$filename') ; $exts = preg_split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } $ext = findexts ($_FILES['images']['name']) ; $ran = rand (); $ran2 = $ran."."; while(list($key,$value) = each($_FILES['images']['name'])) { if(!empty($value)) { $filename = $ran.$value; $filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line $add = "images/$filename"; $insert_query = 'insert into image ( photo ) values ( "'.$filename.'" )'; //echo $_FILES['images']['type'][$key]; // echo "<br>"; copy($_FILES['images']['tmp_name'][$key], $add); chmod("$add",0777); mysql_query($insert_query); } } ?> I am trying to write a script to handle multiple image uploads however i cant get it to work i am a total novice in php so please be kind in your replys :-) [php] <?php $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.JPG','.PNG','.BMP','.GIF'); //These will be the types of file that will pass the validation. $upload_path = '../pic_upload/'; // The place the files will be uploaded to. foreach ($_FILES["pictures"]["error"] as $key => $error) { $filename = $_FILES['pictures']['name'][$key]; $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); if(!empty($filename)) //is it empty { if ($_FILES["pictures"]["size"][$key] >= 9000000) die ('Sorry the picture is too Big!'); } if(!empty($filename)) //Is it empty { if(!in_array($ext,$allowed_filetypes)) //Is the file Allowed die('The file you attempted to upload is not allowed! Pictures only!.'); } if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = $_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name, "$upload_path/$ran$name"); if (!$i++) print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>Untitled Document</title> </head> <body> <div align=\"center\"><img src=\".../image/8-1.gif\" width=\"100\" height=\"100\" /></div> <form id=\"form1\" name=\"form1\" method=\"get\" action=\"reg.php\"> <div align=\"center\"> <input type=\"submit\" name=\"button\" id=\"button\" value=\"Submit\" /> <input type=\"hidden\" name=\"reg\" value=\"6\"> <p>\n"; print "<input type=\"hidden\" name=\"pic$key\" value=\"$ran$name\">\n"; if (!$i++) print "</p> <p> <label> </div> </label> </p> </form> <p> </p> </body> </html>\n"; } } ?> [php] Hi I want to allow users to upload multiple pictures and allow the user to rearrange the order before being uploaded. I have some javascript which populates a select tag with the image names after selecting an image to upload, and some other javascript that allows the users to move the options up and down the list. So it ouputs code such as this to user if they have selected 2 image files for uploading: <select size="6" id="file_list" name="file_list"> <option value="file_0">DSCN2794.JPG</option> <option value="file_1">DSCN2787.JPG</option> </select> I dont know if this is the correct way of approaching it because then in the back end, I use $_FILES, which doesn't care what order the options are in the select tag.... Any advice? Thanks! what's wrong with this ? i can't upload 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 I am in the process of writing a CMS for a friend that is looking to add a classified section to his site. He will be the only one that will ever use it. I got the code to work with one image when he asked me if I could do it so he could post 6 images for each item. I am unable to figure out how to do this. I was told to do this with a while loop. This is the code that I have written so far. <?php //Check to make sure title is filled in. If not redirects to show_add.php if (!$_POST[title]) { header("Location: show_add.php"); exit; } else { //check and see if a session has started session_start(); } //if session has not been properly started redirects back to the administration menu if ($_SESSION[valid] != "yes") { header("Location: admin_menu.php"); exit; } include('includes/connection.php'); //check and see if the type of uploaded file is an image function is_valid_type($file) { $valid_types = array("image/jpg", "image/jpeg", "image/gif", "image/bmp"); if (in_array($file['type'], $valid_types)) return 1; return 0; } //Set Constants $TARGET_PATH = "/home/content/m/i/k/mikedmartiny/html/db_images/"; $title = $_POST['title']; $year = $_POST['year']; $make = $_POST['make']; $model = $_POST['model']; $descript = $_POST['descript']; $image = $_FILES['image']; //Sanitize the inputs $title = mysql_real_escape_string($title); $year = mysql_real_escape_string($year); $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $descript = mysql_real_escape_string($descript); $image['name'] = mysql_real_escape_string($image['name']); //$target_path full string $TARGET_PATH .= $image['name']; //make sure that all fields from form are filled in if ( $title == "" || $year == "" || $make =="" || $model == "" || $descript == "" || $image['name'] == "") { $_SESSION['error'] = "ALL FIELDS ARE REQUIRED!"; header ("Location: show_add.php"); exit; } //check to make sure it has the right file type if (!is_valid_type($image)){ $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header ("Location: show_add.php"); exit; } //check to see if a file with that name exsists if (file_exists($TARGET_PATH)){ $_SESSION['error'] = "A FILE WITH THAT NAME ALL READY EXIST!"; header ("Location: show_add.php"); exit; } //move the image - write path to database while($image <=2) { move_uploaded_file($image['tmp_name'], $TARGET_PATH) } else { // Make sure you chmod the directory to be writeable $_SESSION['error'] = "COULD NOT UPLOAD FILE. CHECK WRITE/REWRITE PERMISSIONS ON THE FILE DIRECTORY!"; header ("Location: show_add.php"); exit; } $sql = "INSERT INTO $table (id, title, year, make, model, descript, image, image_two) VALUES ('', '$_POST[title]', '$_POST[year]', '$_POST[make]', '$_POST[model]', '$_POST[descript]', '" . $image['name'] . "', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); ?> I only have it set up to work with 2 images right now. I thought it would be easier to get it to work properly. Then I could just add in the rest of the info later. Any help would be greatly appreciated. Hello everybody,
i have an easy short code to upload multiple photos to "images" directory.
after upload each file, i give it unique name.
the problem i have is:
i want see the name of uploaded files and print this using echo as in line 21.
the line 21 gives me names but not the same names of uploaded files!
thank you very much for your help.
Rafal
<?php foreach ($_FILES['file']['name'] as $i => $name) { $types = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $name); $extension = end($temp); if ($_FILES["file"]["size"][$i] < 10240000 && in_array($extension, $types)) { if ($_FILES["file"]["error"][$i] > 0) { echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>"; } else { if (file_exists("images/" . $name)) { } else { move_uploaded_file($_FILES["file"]["tmp_name"][$i], "images/" . uniqid() . "." . $extension); echo "uploaded " . $_FILES["file"] , uniqid() . "." . $extension ; echo "<br>"; } } } else { $error = "Invalid file"; } } ?> <html> <head> <title></title> </head> <body> <form enctype="multipart/form-data" action="photo.php" method="POST"> <input type="file" name="file[]" id="file" ><br> <input type="file" name="file[]" id="file" ><br> <input type="file" name="file[]" id="file" ><br> <input type="file" name="file[]" id="file" ><br> <input type="submit" value="upload"> </form> </body> </html> Hello again, guys! I have a couple of questions that I hope anyone can answer. I am making a form that is storing the information in a database, and in this form I also want images to be uploaded. I want to make a function that allows the user to upload as many images as they would like to have in their ad on my website, and I also need something that can handle the upload process, and see how many images the user is trying to upload. Any easy solutions for this? I also have another question: As you can see on the example image underneath this text, I have a form with multiple inputs where the user is suppose to choose how many inputs they want to fill in themself. How should I store this information in the database, and how can I make a script that detects how many of the forms the user actually filled? I hope you guys understood what I was trying to say, and I thank you all anyways. Underneath you can see an image of my forms. Example image: Cheers, Marius Hello all - I'm fairly new to PHP and have been following some online tutorials to learn more, but hit a wall concerning a form that would allow a user to upload an image to his/her specified directory. Basically, I'd like the user to have to put in a password to upload. This "password" would actually just be the name of their directory on the server, so if a user put in "michael83" in as their password, the image would upload to "http://www.mysite.com/images/uploaded/michael83/". Here's my code so far: <form name="newad" method="post" enctype="multipart/form-data" action="upload.php" onSubmit="return validate_form ( );"> <table> <tr><td><input type="file" name="image"></td></tr> <tr><td> </td></tr> <tr><td>Password:</td></tr> <tr><td><input type="text" name="password"></td></tr> <tr><td> </td></tr> <tr><td><input name="Submit" type="submit" value="Upload"></td></tr> </table> </form> <?php define ("MAX_SIZE","1536"); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if(isset($_POST['Submit'])) { $image=$_FILES['image']['name']; $dir=$_POST['username']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "pdf") && ($extension != "gif")) { echo '<h4>Sorry, your file is an unknown extension.</h4>'; $errors=1; } else { $size=filesize($_FILES['image']['tmp_name']); if ($size > MAX_SIZE*1024) { echo '<h4>Sorry, you have exceeded the size limit.</h4>'; echo '<p>If you need more help with this, please <a href="#">contact us</a> directly.</p>'; $errors=1; } $newname="images/uploaded/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h4>Oops, looks like the upload was unsuccessfull.</h4>'; echo '<p>If you continue to have problems, please <a href="#">contact us</a>.</p>'; $errors=1; }}}} if(isset($_POST['Submit']) && !$errors) { echo "<h4>Your file was uploaded successfully!</h4><br><br>"; echo '<a href="http://www.mysite.com/' . $newname . '">http://www.mysite.com/' . $newname . '</a><br><br>'; } ?> Any help would be greatly appreciated. Many thanks in advance! EDIT Note: I would be the one setting the directories up, so if the user enters a "password" (directory) that doesn't exist, the form would return an error. 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 Hello I am having problems uploading an image through a HTML form. I want the image to be uploaded to the server and the image name to be written to the mysql database. Below is the code I am using: Code: [Select] <?php if (isset($_POST['add'])){ echo "<br /> add value is true"; $name = $_POST['name']; $description = $_POST['description']; $price = $_POST['price']; $category_id = $_POST['category_name']; $image = $_FILES['image']['name']; //file path of the image upload $filepath = "../images/"; //mew name for the image upload $newimagename = $name; //new width for the image $newwidth = 100; //new height for the image $newheight = 100; include('../includes/image-upload.php'); mysql_query("INSERT INTO item (item_name, item_description, item_price, item_image) VALUES ('$name','$description','$price','$image')"); ?> Here is the image-upload.php file code: Code: [Select] <?php //assigns the file to the image $image =$_FILES["image"]["name"]; $uploadedfile =$_FILES["image"]["tmp_name"]; if ($image) { //retrieves the extension type from image upload $extension = getextension($image); //converts extension to lowercase $extension = strtolower($extension); //create image from uploaded file type if($extension=="jpg" || $extension=="jpeg") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); }else if($extension=="png") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefrompng($uploadedfile); }else{ $src = imagecreatefromgif($uploadedfile); } //creates a list of the width and height of the image list($width,$height)=getimagesize($uploadedfile); //adds color to the image $tmp = imagecreatetruecolor($newwidth,$newheight); //create image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); //set file name $filename = $filepath.$newimagename.".".$extension; $imagename = $newimagename.".".$extension; //uploads new file with name to the chosen directory imagejpeg($tmp,$filename,100); //empty variables imagedestroy($src); imagedestroy($tmp); } ?> Any help would be appreciated, fairly new to all this! Thanks!!! hello friends, while clicking the form all the information goes to database, I have one image upload field, when cliking the submit button, i would like 'image name' to go in database and file to go in /upload folder, i have tried this for hours and gave up, if anyone help me in this, i would be very greatful |