PHP - Php Dropzone Image Upload With Multiple Form Inputs
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.
Similar TutorialsHow 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()); I 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."'>"; ?> I generated a table from the database, and at the end of each row there are two submits, one for save and another for delete. The values are generated as either text and select box input. Right now, I have all the submits named differently (ends a number), so I can loop through all available submits based on the number to check which row needs to be updated, and to retrieve the values during form processing, then only perform the query. I have also hidden input in each row to send the "primary key" that is used during query. Is there a better approach than to have so many different names for the buttons, not having to loop through all of them each time, and still keep a similar layout? I'm trying to avoid anything else than PHP. The table looks something like: col1____| col2_______| col3____|__________________ txt input | select input | txt input |save bttn | delete bttn txt input | select input | txt input |save bttn | delete bttn /*I'm trying to use dropzone js plugin for drag/drop single phote but it require me to create another form for file upload, but i want to use single form for both image and name input, i have no idea on how to combine this field in sinle request, the form to submit both image and name look like*/ <form method="POST" enctype="multipart/form-data"> <input type="text" name="name" id="name"> <!--how to replace this field with dropzone but in this form in order to use the same ajax as below--> <input type="file" name="photo" id="photo"> <button type="submit">send</button> </form> //ajax, how to add dropzone data in $("form").on('submit', function(e) { $.ajax({ url: 'add.php', type: 'POST', data: new FormData(this), dataType: 'JSON', contentType: false, cache: false, processData:false, }).done( function (data) { if(data.success == false) { //for error message response if(data.errors.name) { $('#name').append('<span class="text-danger">' + data.errors.name + '</span>'); } if(data.errors.photo) { $('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>'); } } }); e.preventDefault(); });
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] <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); } } ?> Hey guys. I'm using this script to handle file (picture) uploads at the moment, and it works fine. Problem is though, I need to changeit to a multiple upload form (with 10 uploads per submit) and I dont know how to do it. I think ... I need to change this "<input type="file" name="image" >" to an array ... and put a "for each" loop or something somewhere ... but I really don't know what I am doing. Can someone please help? Thanks Gem <?php include ("includes/dbconnect120-gem.php"); //define a maxim size for the uploaded images define ("MAX_SIZE","500"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","150"); define ("HEIGHT","100"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // 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; if(isset($_POST['submit1']) && !$errors) { $sqlalbum="INSERT INTO album (album_name) VALUES ('$_POST[newalbumname]')"; mysql_query($sqlalbum) or die ('Error, album_query failed : ' . mysql_error()); } // checks if the form has been submitted if(isset($_POST['Submit'])) { //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, print an error message //and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { 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=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > 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=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="uploads/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='uploads/thumbs/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters //the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { $album = $_POST['album']; $query = "INSERT INTO upload (name, path, album_id, thumbpath ) ". "VALUES ('$image_name', '$newname' , '$album', '$thumb_name')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } ?> <!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> <form name="newalbum" method="post" action=""> <input name="newalbumname" type="text" size="30" maxlength="30" value="<?php echo $newalbumname; ?>" /> <input type="submit" name="submit1" value="Create Album" /> </form> <br /> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><select name="album"> <option value="select" selected="selected" >-Albums-</option> <?php $asql="select * from album order by album_id DESC"; $aresult=mysql_query($asql) or die(mysql_error());; while($arow=mysql_fetch_array($aresult)) { $album_id=$arow['album_id']; $album_name=$arow['album_name']; ?> <option value="<?php echo $album_id; ?>"><?php echo $album_name; ?></option> <?php } ?> </select> <tr><td><input type="file" name="image" ></td></tr> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr> </table> </form> </body> </html> 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! Hi, I have been trying to create a site where you can list multiple items with a picture for each but I can't get the upload form working. Here's what I've got: <?php include "/home/a9653716/public_html/header.inc"; ?> <body> <table border="0" width="100%"><tr> <td valign="top" width="800"> <?php echo "<div id='content'>"; echo "<h2 div id='title'>"; echo "Create a listing"; echo "</h2>"; //////content////////////////////////// if($_SESSION['uid']){ $id = mss($_POST['id']); $no_w =($_POST['want']); $no_o =($_POST['offer']); $wantbtn = ($_POST['addwantbtn']); $offerbtn = ($_POST['addofferbtn']); if ($wantbtn) echo "Want <br />"; $no_want = ($_POST['no_want']); $no_offer = ($_POST['no_offer']); if (!$no_w){ if ($no_want){ $no_w = $no_want; }else $no_w = 3; } if (!$no_o){ if ($no_offer){ $no_o = $no_offer; }else $no_o = 3; } if ($no_o > 20){ $no_o = 20; } if ($no_w > 20){ $no_w = 20; } $offerid = 1; $wantid = 1; $addofferlimit = 20 - $no_o + 1; $addwantlimit = 20 - $no_w + 1; $addoffer = 1; $addwant = 1; $addmorewants = ($_POST['addmorewants']); $addmoreoffers = ($_POST['addmoreoffers']); if ($wantbtn){ $no_w = $addmorewants; } if ($offerbtn){ $no_o = $addmoreoffers; } if ($id) { $sql = "SELECT * FROM `item_sub_cats` WHERE `id`='" . $id . "'"; $res = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($res) == 0) { echo "The category you are trying to create a listing on, does not exist!\n"; } else { $row1 = mysql_fetch_assoc($res); if (!$_POST['submit']) { echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n"; echo "<form method=\"post\" action=\"./create_listing.php\">\n"; echo "<tr><td>Sub Category</td><td><select name=\"cat\">\n"; $sql2 = "SELECT * FROM `item_cats`"; $res2 = mysql_query($sql2); while ($row = mysql_fetch_assoc($res2)) { $sql3 = "SELECT * FROM `item_sub_cats` WHERE `cid`='" . $row['id'] . "'"; $res3 = mysql_query($sql3) or die(mysql_error()); echo "<option value=\"0\">" . $row['name'] . "</option>\n"; while ($row2 = mysql_fetch_assoc($res3)) { $selected = ($row2['id'] == $id) ? " SELECTED" : ""; echo "<option value=\"" . $row2['id'] . "\"" . $selected . "> " . $row2['name'] . "</option>\n"; } } echo "</select></td></tr>\n"; echo "<tr><td>Listing Title</td><td><input type=\"text\" name=\"title\" size=\"53\"></td></tr>\n"; ?> <script>edToolbar('message'); </script> <?php echo "<tr><th colspan='2'><b>What you have to offer!</b><br /><br />Change to <select name='addmoreoffers'>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addofferbtn'><br /></th></tr>"; //offer while loop// while ($offerid <= $no_o){ echo "<tr><td>Item $offerid</td><td><input type='textbox' value='title' size='40' name='offer$offerid'> <input type='textbox' value='pts' size='7' name='offer" . $offerid . "pts'></td></tr>"; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='offer" . $offerid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='offer" . $offerid . "img'></td></tr>"; $offerid ++; } //end offer while loop// //want while loop// echo "<tr><th colspan='2'><b>What you want!</b><br /><br />Change to <select>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addwantbtn'><br /></th></tr>"; while ($wantid <= $no_w){ echo "<tr><td>Item $wantid</td><td><input type='textbox' size='40' value='title' name='want" . $wantid . "title'> <input type='textbox' value='pts' size='7' name='want" . $wantid . "pts'></td></tr>"; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='want" . $wantid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='want" . $wantid . "img'></td></tr>"; $wantid ++; } //end want while loop// echo "<tr><td>Other Details</td><th colspan='2'><textarea cols='50' rows='10' id=\"message\" name=\"message\"></textarea></th></tr>\n"; echo "<tr><td colspan=\"2\" align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Create Listing\"></td></tr>\n"; echo "</form></table>\n"; } else { $cat = mss($_POST['cat']); $title = mss($_POST['title']); $details = mss($_POST['message']); if ($cat && $title && $details) { $sql = "SELECT * FROM `item_sub_cats` WHERE `id`='" . $cat . "'"; $res = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($res) == 0) { echo "This sub category does not exist!\n"; } else { $row = mysql_fetch_assoc($res); if (strlen($title) < 3 || strlen($title) > 32) { echo "The title must be between 3 and 32 characters!\n"; } else { if (strlen($details) < 3 || strlen($details) > 10000) { echo "The message must be between 3 and 10,000 characters!\n"; } else { $date = date("m-d-y") . " at " . date("h:i:s"); $time = time(); $sql2 = "INSERT INTO `listing_topics` (`cid`,`title`,`uid`,`date`,`time`,`message`,) VALUES('" . $cat . "','" . $title . "','" . $_SESSION['uid'] . "','" . $date . "','" . $time . "','" . $details . "')"; $res2 = mysql_query($sql2) or die(mysql_error()); $tid = mysql_insert_id(); topic_go($tid); } } } } else { } } } } else { if (!$_POST['submit']) { echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n"; echo "<form method=\"post\" action=\"./create_listing.php\">\n"; echo "<tr><td>Sub Category</td><td><select name=\"cat\">\n"; $sql2 = "SELECT * FROM `item_cats`"; $res2 = mysql_query($sql2) or die(mysql_error()); while ($row = mysql_fetch_assoc($res2)) { $sql3 = "SELECT * FROM `item_sub_cats` WHERE `cid`='" . $row['id'] . "'"; $res3 = mysql_query($sql3) or die(mysql_error()); echo "<option value=\"0\">" . $row['name'] . "</option>\n"; while ($row2 = mysql_fetch_assoc($res3)) { $selected = ($row2['id'] == $id) ? " SELECTED" : ""; echo "<option value=\"" . $row2['id'] . "\"" . $selected . "> " . $row2['name'] . "</option>\n"; } } echo "</select></td></tr>\n"; echo "<tr><td>Listing Title</td><td><input type=\"text\" name=\"title\" size=\"53\"></td></tr>\n"; ?> <script>edToolbar('message'); </script> <?php echo "<tr><th colspan='2'><b>What you have to offer!</b><br /><br />Change to <select name='addmoreoffers'>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addofferbtn'><br /></th></tr>"; //offer while loop// while ($offerid <= $no_o){ $offername = "offer" . "$offerid"; echo "<tr><td>Item $offerid</td><td><input type='textbox' value='title' size='40' name='$offername'> <input type='textbox' value='pts' size='7' name='offer" . $offerid . "pts'></td></tr>"; echo $offername; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='offer" . $offerid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='offer" . $offerid . "img'></td></tr>"; $offerid ++; } //end offer while loop// //want while loop// echo "<tr><th colspan='2'><b>What you want!</b><br /><br />Change to <select name='addmorewants'>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addwantbtn'><br /></th></tr>"; while ($wantid <= $no_w){ $wantname = "want" . "$wantid"; echo "<tr><td>Item $wantid</td><td><input type='textbox' size='40' value='title' name='$wantname'> <input type='textbox' value='pts' size='7' name='want" . $wantid . "pts'></td></tr>"; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='want" . $wantid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='want" . $wantid . "img'></td></tr>"; $wantid ++; } //end want while loop// echo "<tr><td>Other Details</td><th colspan='2'><textarea cols='50' rows='10' id=\"message\" name=\"message\"></textarea></th></tr>\n"; echo "<tr><td colspan=\"2\" align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Create Listing\"></td></tr>\n"; echo "<input type='hidden' name='no_offer' value='$no_o'>"; echo "<input type='hidden' name='no_want' value='$no_w'>"; echo "</form></table>\n"; } else { $cat = mss($_POST['cat']); $title = mss($_POST['title']); $details = mss($_POST['message']); $o_title_count = 1; $filled_o = 1; $offer_no_values=1; $w_title_count = 1; $filled_w = 1; $want_no_values=1; while ($filled_o && $filled_o != "title"){ $o_title_count = "offer" . "$offer_no_values"; $filled_o = ($_POST["$o_title_count"]); $offer_no_values++; } $offer_no_values=$offer_no_values-2; echo "Number of offer titles:" . $offer_no_values . "<br />"; while ($filled_w && $filled_w != "title"){ $w_title_count = "want" . "$want_no_values"; $filled_w = ($_POST["$w_title_count"]); $want_no_values++; } $want_no_values=$want_no_values-2; echo "number of want titles:" . $want_no_values . "<br />"; echo "cat: " . $cat . "<br />"; echo "title: " . $title . "<br />"; echo "message: " . $details . "<br />"; echo "want_no_values: " . $want_no_values . "<br />"; echo "offer_no_values: " . $offer_no_values . "<br />"; if ($cat && $title && ($want_no_values >= 1) && ($offer_no_values >= 1)) { ////////////////////////////////////////////////////// ////////////////////want construct//////////////////// ////////////////////////////////////////////////////// $x=1; while ($x <= $want_no_values){ $w_points = "want" . $x . "pts"; $w_desc = "want" . $x . "desc"; $w_image = "want" . $x . "img"; if ($w_image){ $w_img_name = $_FILES['want1img']['name']; $w_img_type = $_FILES['$w_image']['type']; $w_img_size = $_FILES['$w_image']['size']; $w_img_tmpname = $_FILES['$w_image']['tmp_name']; $w_img_ext = substr($w_img_name, strpos($w_img_name, '.')); echo "w name:" . $w_img_name . "<br />"; print_r ($_FILES['want1img']); } if ($w_img_name){ move_uploaded_file($w_img_tmpname, "images/listings/$username" . "-" . "$w_img_name" . "-" . "$w_img_size" . "$ext") or die(mysql_error()); $w_image = "$username" . "-" . "$w_img_name" . "-" . "$w_img_size" . "$ext"; } echo $w_points; $w_item_name = ($_POST["want$x"]); $w_item_pts = ($_POST["$w_points"]); $w_item_desc = ($_POST["$w_desc"]); $want_item = "<tr><td width='25'></td><th colspan='3'><b>" . $w_item_name . "</b> - " . $w_item_pts . "pts</th></tr> <tr><td width='25'></td><td width='25'></td><th colspan='2'>" . $w_item_desc . $w_image . "</th></tr>"; $want_items = $want_items . $want_item; $x++; } $want_desc = "<table> <tr><th colspan='3'><h3>What I want!</h3></th></tr>" . $want_items . "</table>"; ////////////////////////////////////////////////////// ////////////////////offer construct/////////////////// ////////////////////////////////////////////////////// $x=1; while ($x <= $offer_no_values){ $o_points = "offer" . $x . "pts"; $o_desc = "offer" . $x . "desc"; echo $w_points; $o_item_name = ($_POST["offer$x"]); $o_item_pts = ($_POST["$o_points"]); $o_item_desc = ($_POST["$o_desc"]); $offer_item = "<tr><td width='25'></td><th colspan='3'><b>" . $o_item_name . "</b> - " . $o_item_pts . "pts</th></tr> <tr><td width='25'></td><td width='25'></td><th colspan='2'>" . $o_item_desc . "</th></tr>"; $offer_items = $offer_items . $offer_item; $x++; } $offer_desc = "<table> <tr><th colspan='3'><h3>What I offer!</h3></th></tr>" . $offer_items . "</table>"; $desc=$want_desc . $offer_desc; echo $desc; } else { echo "Please supply all the fields!\n"; } } } } else echo "You must be logged in to see this page!"; ?> </td><td width="250"> <?php include("sidebar.inc"); ?> </td> </table> </body> </html> <?php include("footer.inc"); ?> I know it's very messy, I'll probably end up rewriting it but this is what I get after supplying the right fields and uploading an image for the want section: Code: [Select] Number of offer titles:1 number of want titles:1 cat: 1 title: This is the title message: None still testing it! want_no_values: 1 offer_no_values: 1 w img name: want1ptswant1pts The only bit that is of any use is the name section: Code: [Select] w img name: Nothing is recieved and the file is not uploaded!! I probably have missed something out but I am very new to php so please help!! Thanks Cameron what's wrong with this ? i can't upload Hello, this question was already answered on this form but the answer was deleted by admin a year or so ago. anyway, I have an edit items page with multiple images and I do not want to have to relocate all of the images manually but if I do not then an empty variable is passed to mysql, thus deleting my image. What do I need to know to write a code that will not pass an empty variable to my table? Do I use sprint? 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>
I have a hopefully small issue on a form submitting data to the mysql database table and email. The email side works fine as does the adding the data to the database table but if I upload two files, it stores the support ticket twice in the database table where as I want to store just once and the files be stored as a array in the database table. I got the code from the link https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
<?php require_once "registerconfig.php"; if (isset($_POST['submit'])) { // File upload configuration $targetDir = "support-ticket-images/"; $allowTypes = array('pdf','doc','docx','jpg','png','jpeg','gif'); $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; // Escape user inputs for security $ticket_subject = htmlentities($_POST['ticket_subject'], ENT_QUOTES); $ticket_message = strip_tags($_POST['ticket_message'], ENT_QUOTES); $ticket_status ='PENDING SUPPORT'; $username = htmlentities($_SESSION["user_name"], ENT_QUOTES); $user_id = htmlentities($_SESSION["user_id"], ENT_QUOTES); $fileNames = array_filter($_FILES['files']['name']); if(!empty($fileNames)){ foreach($_FILES['files']['name'] as $key=>$val){ // File upload path $fileName = basename($_FILES['files']['name'][$key]); $targetFilePath = $targetDir . $fileName; // Check whether file type is valid $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ // Image db insert sql $insertValuesSQL .= "('".$ticket_subject."','".$ticket_message."','".$fileName."','".$ticket_status."','".$username."', '".$user_id."'),"; }else{ $errorUpload .= $_FILES['files']['name'][$key].' | '; } }else{ $errorUploadType .= $_FILES['files']['name'][$key].' | '; } } if(!empty($insertValuesSQL)){ $insertValuesSQL = trim($insertValuesSQL, ','); // Insert image file name into database $insert = $link->query("INSERT INTO DB TABLE NAME (ticket_subject, ticket_message, file_name, ticket_status, user_name, user_id) VALUES $insertValuesSQL"); if($insert){ $to = "emailaddress"; $subject = "A new support ticket has been submitted"; $message = " <strong>$username</strong> has just created a support ticket, below is the support ticket <br /><br /> <u>Support Ticket Details</u> <br /><br> <strong>Support Ticket Subject</strong>: $ticket_subject <br/><br><strong>Support Ticket Message</strong>: $ticket_message <p><strong><u>Support Ticket Files</u></strong> <br> <img src='$fileName'> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // More headers $headers .= 'From: <noreply@emailaddress>' . "\r\n"; $mail=mail($to,$subject,$message,$headers); $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; header("location: support-ticket-confirmation?user=$username"); }else{ $statusMsg = "Sorry, there was an error uploading your file."; } } }else{ $statusMsg = 'Please select files to upload.'; } // Display status message echo $statusMsg; } ?> The structure of the db table column is file_name, VARCHAR(255), latin1_swedish_ci, NOT NULL 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 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. How is it possible, in PHP, to display an error message next to a form input text field if a user is attempting to submit a form with empty fields? Moreover, how is it possible to remove the same error message when the user fills in the input field with the required data and/or refreshes the page? I have 2 files that I am working with: application.php and process.php.
application.php mainly has the HTML of the form. I am very new to learning PHP (I started learning it last week) and I have been searching for hours for a clear answer. I have already tried different methods for generating the error message including: using empty(), !isset, $_POST["name"] = "", etc, and have tried using session_start();, $row, echo, print, and other variables to try and display error message on the page, and I have tried using unset();, and = null, to try and remove the error message once the input field has been filled but all to no avail. Either the method I try only half works, or nothing works, and I cannot pinpoint which is the part that is not working. I only have 2 files to work with, and as an example of what I want to do is:
1. If the first name field is empty when the user clicks submit, an error message should appear next to the input. Is this possible with PHP? |