PHP - Image Upload Form (to User-specified Dir)
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. Similar TutorialsHi again: What I want to do - and am stuck on - is to allow the user to add files to the feedback, submit the form, and the data will get stored in the DB (and the uploaded files will get stored in "uploads"), plus an email will get sent to the client who can click the files links in the email, and download them that way. I have done this via ASP, but never tried it with PHP ... This is what my database table looks like" Code: [Select] CREATE TABLE `myProductRightData2` ( `myDate` varchar(55) default NULL, `myNameAndProduct` text, `myWebsite` text, `myProductUse` text, `myProductProblemSolver` text, `myProductUnique` text, `myWhyBetter` text, `myProductAppeal` text, `myProductSelling` text, `myProductResearch` text, `file1` varchar(255) default NULL, `myProductStory` text, `mySpokesperson` text, `myProductReviewed` text, `myProductDecision` text, `file2` varchar(255) default NULL, `file3` varchar(255) default NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `myProductRightData2` -- INSERT INTO `myProductRightData2` VALUES('February 22, 2011', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test.pdf', 'test', 'test', 'test', 'test1.jpg', 'test2.jpg'); And this is the form code: Code: [Select] <?php $error = NULL; $myDate = NULL; $myNameAndProduct = NULL; $myPhone = NULL; $myEmail = NULL; $myWebsite = NULL; $myProductUse = NULL; $myProductProblemSolver = NULL; $myProductUnique = NULL; $myWhyBetter = NULL; $myProductAppeal = NULL; $myProductSelling = NULL; $myProductResearch = NULL; $file1 = NULL; $myProductStory = NULL; $mySpokesperson = NULL; $myProductReviewed = NULL; $myProductDecision = NULL; $file2 = NULL; $file3 = NULL; if(isset($_POST['submit'])) { if ((($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/pjpeg")) && ($_FILES["file1"]["size"] < 20000)) { if ($_FILES["file1"]["error"] > 0) { echo "Return Code: " . $_FILES["file1"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file1"]["name"] . "<br />"; echo "Type: " . $_FILES["file1"]["type"] . "<br />"; echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file1"]["name"])) { echo $_FILES["file1"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["file1"]["name"]); echo "Stored in: " . "uploads/" . $_FILES["file1"]["name"]; } } } else { echo "Invalid file"; } $myDate = $_POST['myDate']; $myNameAndProduct = $_POST['myNameAndProduct']; $myPhone = $_POST['myPhone']; $myEmail = $_POST['myEmail']; $myWebsite = $_POST['myWebsite']; $myProductUse = $_POST['myProductUse']; $myProductProblemSolver = $_POST['myProductProblemSolver']; $myProductUnique = $_POST['myProductUnique']; $myWhyBetter = $_POST['myWhyBetter']; $myProductAppeal = $_POST['myProductAppeal']; $myProductSelling = $_POST['myProductSelling']; $myProductResearch = $_POST['myProductResearch']; $file1 = $_POST['file1']; $myProductStory = $_POST['myProductStory']; $mySpokesperson = $_POST['mySpokesperson']; $myProductReviewed = $_POST['myProductReviewed']; $myProductDecision = $_POST['myProductDecision']; $file2 = $_POST['file2']; $file3 = $_POST['file3']; if(empty($myNameAndProduct)) { $error .= '-- Enter your Name and Product. <br />'; } if(empty($myPhone)) { $error .= '-- Enter your Phone Number. <br />'; } if(empty($myEmail)) { $error .= '-- Enter your Email. <br />'; } if($error == NULL) { $sql = sprintf("INSERT INTO myProductRightData2(myDate,myNameAndProduct,myPhone,myEmail,myWebsite,myProductUse,myProductProblemSolver,myProductUnique,myWhyBetter,myProductAppeal,myProductSelling,myProductResearch,file1,myProductStory,mySpokesperson,myProductReviewed,myProductDecision,file2,file3) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')", mysql_real_escape_string($myDate), mysql_real_escape_string($myNameAndProduct), mysql_real_escape_string($myPhone), mysql_real_escape_string($myEmail), mysql_real_escape_string($myWebsite), mysql_real_escape_string($myProductUse), mysql_real_escape_string($myProductProblemSolver), mysql_real_escape_string($myProductUnique), mysql_real_escape_string($myWhyBetter), mysql_real_escape_string($myProductAppeal), mysql_real_escape_string($myProductSelling), mysql_real_escape_string($myProductResearch), mysql_real_escape_string($file1), mysql_real_escape_string($myProductStory), mysql_real_escape_string($mySpokesperson), mysql_real_escape_string($myProductReviewed), mysql_real_escape_string($myProductDecision), mysql_real_escape_string($file2), mysql_real_escape_string($file3)); if(mysql_query($sql)) { $error .= 'Thank you for submitting your product. We will be in contact with you soon.'; mail( "m@sp.com", "Product Submission", "Date Sent: $myDate\n Name and Product: $myNameAndProduct\n Phone: $myPhone\n Email: $myEmail\n Website: $myWebsite\n Product Use: $myProductUse\n Problem Product Solves: $myProductProblemSolver\n Product Uniqueness: $myProductUnique\n Product Better Because: $myWhyBetter\n Product Appeal: $myProductAppeal\n Product Selling Places: $myProductSelling\n Product Research: $myProductResearch\n Research Documentation: $file1\n Product Story: $myProductStory\n Product Spokesperson: $mySpokesperson\n Product Reviewed: $myProductReviewed\n Product Decision Maker: $myProductDecision\n Samples: $file2\n $file3", "From: $Email" ); } else { $error .= 'There was an error in our database, please try again!'; } } } echo '<span class="textError">' . $error . '</span>'; ?> <form name="myform" action="" method="post" enctype="multipart/form-data"> <input type="hidden" name="myDate" size="45" maxlength="50" value="<?php echo date("F j, Y"); ?>" /> What is the name of your company and product? <textarea name="myNameAndProduct" cols="72" rows="1"><?php echo $myNameAndProduct; ?></textarea> What is your phone number? <textarea name="myPhone" cols="72" rows="1"><?php echo $myPhone; ?></textarea> What is your email? <textarea name="myEmail" cols="72" rows="1"><?php echo $myEmail; ?></textarea> website we can visit for more information? <textarea name="myWebsite" cols="72" rows="1"><?php echo $myWebsite; ?></textarea> What is this product used for? <textarea name="myProductUse" cols="72" rows="3"><?php echo $myProductUse; ?></textarea> Does this product solve a problem? If so, how? <textarea name="myProductProblemSolver" cols="72" rows="3"><?php echo $myProductProblemSolver; ?></textarea> Does your product have unique or cutting-edge features, ingredients or benefits? <textarea name="myProductUnique" cols="72" rows="3"><?php echo $myProductUnique; ?></textarea> What makes it better than similar products? <textarea name="myWhyBetter" cols="72" rows="3"><?php echo $myWhyBetter; ?></textarea> Does this product have mass appeal? Who is the target audience? <textarea name="myProductAppeal" cols="72" rows="3"><?php echo $myProductAppeal; ?></textarea> Is this product currently selling elsewhere? If so, where and what is the retail price? <textarea name="myProductSelling" cols="72" rows="3"><?php echo $myProductSelling; ?></textarea> Do you have independent research to prove claims about this product? Please provide copies. <textarea name="myProductResearch" cols="72" rows="3"><?php echo $myProductResearch; ?></textarea> Upload independent research copies (Word or PDF files): <input type="file" name="file1" id="file1" /> How and why did your company start? Does that "story" make this product more interesting? <textarea name="myProductStory" cols="72" rows="3"><?php echo $myProductStory; ?></textarea> Do you have a passionate spokesperson that would be comfortable presenting on TV? <textarea name="mySpokesperson" cols="72" rows="3"><?php echo $mySpokesperson; ?></textarea> Has this product ever been submitted to QVC for review? If yes, please provide the details. <textarea name="myProductReviewed" cols="72" rows="3"><?php echo $myProductReviewed; ?></textarea> Who from your company will make the decision to proceed if QVC is presents the right opportunity? <textarea name="myProductDecision" cols="72" rows="3"><?php echo $myProductDecision; ?></textarea> Upload two samples of your product for review (.JPG or PDF files): <input type="file" name="file2" id="file2" /> <input type="file" name="file3" id="file3" /> <input type="submit" name="submit" value="Submit New Product" class="submitButtonProduct" /><br /> </form> It's essentially the same feedback for I always use and it works fine, but I have been trying to integrate the upload portion into it from a tutorial I found on W3C: http://www.w3schools.com/PHP/php_file_upload.asp Any ideas on how to make this work? 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 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()); 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. 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."'>"; ?> 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.
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 ...and the file is to be copied into a folder created by me. I was wondering what the file path would be for Windows, since it does not seem to recognise the file path that I have chosen: Upload Form code: Code: [Select] <html> <head><title>Car Accident Report Uploader</title></head> <body> <form action="fileuploadform.php" method="post" enctype="multipart/form-data"> <input type="file" size="45" name ="file"><br> <input type="submit" value = "Upload Car Accident Report"> </form> </body> </html> Copying Script Code: Code: [Select] <?php if ($_FILES['file']['name'] !="") { copy ($_FILES['file']['tmp_name'], 'C:\xampp\htdocs\rcm' . $_FILES['file']['name']) or die ("Could not copy Car Accident Report Form"); } else {die ("No Car Accident Report Form has been chosen");} ?> <html> <head><title>Car Accident Report Form Upload Complete</title></head> <body><h3>Car Accident Report Form has been uploaded</h3> <ul> <li>Sent: <?php echo $_FILES['file']['name']; ?> <li>Size: <?php echo $_FILES['file']['size']; ?> bytes <li>Type: <?php echo $_FILES['file']['type']; ?> <a href = "<?php echo $_FILES['file']['name']; ?>"> Click here to view the Car Accident Report Form</a> </body> </html> If anyone can help me find the relevant file path, it would be appreciated! Hello! I want to make the users in the website able only to upload, for example, 1 GB, so that when a user finishes the 1 GB available for his files, he cannot upload more files. I know how to set up upload limit for a single file in the upload page, or even globally for anyone to upload. But I would like to know how to make each user has specific capacity, and how it is updated so that if he uploads 0.5 GB he has only 0.5 GB left. I thought of creating a column in the `users` or something concerning upload limit that I will set it (one GB for example). If I will do that, how will I be able to determine how much he uploaded? Any help would be appreciated. Thank you! i have my upload process working that uploads documents to the server and then displays in onto the user page like this:
<?php function find_all_files($dir) { $root = scandir($dir); foreach($root as $value) { if($value === '.' || $value === '..') {continue;} if(is_file("$dir/$value")) {$result[]="$dir/$value"; continue; } foreach(find_all_files("$dir/$value") as $value) { $result[]=$value; } } return $result; } $fileupload = 'fileupload'; $getem = find_all_files($fileupload); foreach($getem as $key => $value) { echo '<a href="'.$value.'">'.$value.'</a><br />'; } ?> <?php if($handle = opendir('members/')) { while (false !== ($entry = readdir($handle))) { if($entry != "." && $enrty != "..") { echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n"; } } closedir($handle); } ?>here they can download the files to their computer however is there a way to only display the file of the user that is logged in through their session? Hi all, I am quite new to PHP and MySql. I know how to upload a file a and save the path in the DB, but now I need to send an automatic email to the user when a new invoice is added to his directory. Please help. Thanks I need a way a user can upload a file onto my website(it's a shared site, I believe, but I own the domain), I've tried using the cURL library but it seems a bit over my head at the moment. And everything I tried with it would not result in a file being uploaded into any folder. What can I do what I need? I've searched around and never found anything that worked for me. 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!!! Hi- the code below lets me upload a CSV file to my database if I have 1 field in my database and 1 column in my CSV. I need to add to my db "player_id" from the CVS file and "event_name" and "event_type" from the form... any ideas??? here's the code: Code: [Select] <?php $hoststring =""; $database = ""; $username = ""; $password = ""; $makeconnection = mysql_pconnect($hoststring, $username, $password); ?> <?php ob_start(); mysql_select_db($database, $makeconnection); $sql_get_players=" SELECT * FROM tabel ORDER BY player_id ASC"; // $get_players = mysql_query($sql_get_players, $makeconnection) or die(mysql_error()); $row_get_players = mysql_fetch_assoc($get_players); // $message = null; $allowed_extensions = array('csv'); $upload_path = '.'; //same directory if (!empty($_FILES['file'])) { if ($_FILES['file']['error'] == 0) { // check extension $file = explode(".", $_FILES['file']['name']); $extension = array_pop($file); if (in_array($extension, $allowed_extensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) { if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) { $keys = array(); $out = array(); $insert = array(); $line = 1; while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) { foreach($row as $key => $value) { if ($line === 1) { $keys[$key] = $value; } else { $out[$line][$key] = $value; } } $line++; } fclose($handle); if (!empty($keys) && !empty($out)) { $db = new PDO( 'mysql:host=host;dbname=db', 'user', 'pw'); $db->exec("SET CHARACTER SET utf8"); foreach($out as $key => $value) { $sql = "INSERT INTO `table` (`"; $sql .= implode("`player_id`", $keys); $sql .= "`) VALUES ("; $sql .= implode(", ", array_fill(0, count($keys), "?")); $sql .= ")"; $statement = $db->prepare($sql); $statement->execute($value); } $message = '<span>File has been uploaded successfully</span>'; } } } } else { $message = '<span>Only .csv file format is allowed</span>'; } } else { $message = '<span>There was a problem with your file</span>'; } } ob_flush();?> <!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>CSV File Upload</title> </head> <body> <form class="form" action="" method="post" enctype="multipart/form-data"> <h3>Select Your File</h3> <p><?php echo $message; ?></p> <input type="file" name="file" id="file" size="30" /> <br/> <label>Event Name:</label><input name="event_name" type="text" value="" /> <br/> <label>Event Type:</label><input name="event_type" type="text" value="" /> <br/> <input type="submit" id="btn" class="button" value="Submit" /> </form> <br/> <h3>Results:</h3> <?php do { ?> <p><?php echo $row_get_players['player_id'];?></p> <?php } while ($row_get_players = mysql_fetch_assoc($get_players)); ?> </body> </html> 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 I need code for upload images for php as well as to edit that image
Hi, Im rather new to php and really unable to get the above to work. Everything works apart from the image being resized. File is uploaded, and the image name is printed into the SQL database. But i cant for the life of me get the image to go to 300x200? If you could help me i would be very grateful My code for the form processing page is attached. Ive put a few line breaks into the code as to where i think is the issue. I just cant seem to resize the image. Does the image resize need to come before the part it writes the image to the server or can this be done afterwards? Please help. P.S - Thanks in advance Hi everybody, I have similar problem like member vikaspa in this thread: http://www.phpfreaks.com/forums/index.php?topic=279531.msg1323820#msg1323820 Have great site, but this image rewriting makes me crazy...today someone upload in some thread 1.jpg for example...after 3 days someone uploads diferent image and also called it 1.jpg, and overwrites this earlier one. Nonsense. Please help me with my code, what to add where, to prevent rewriting and instead that, to rename upload internally (without notifying the user)...for example 1_1.jpg. Here is my code: Code: [Select] if ($fdata['forum_attach'] && checkgroup($fdata['forum_attach'])) { $attach = $_FILES['attach']; if ($attach['name'] != "" && !empty($attach['name']) && is_uploaded_file($attach['tmp_name'])) { $attachname = stripfilename(substr($attach['name'], 0, strrpos($attach['name'], "."))); $attachext = strtolower(strrchr($attach['name'],".")); if (preg_match("/^[-0-9A-Z_\[\]]+$/i", $attachname) && $attach['size'] <= $settings['attachmax']) { $attachtypes = explode(",", $settings['attachtypes']); if (in_array($attachext, $attachtypes)) { $attachname .= $attachext; move_uploaded_file($attach['tmp_name'], FORUM."attachments/".$attachname); chmod(FORUM."attachments/".$attachname,0644); if (in_array($attachext, $imagetypes) && (!@getimagesize(FORUM."attachments/".$attachname) || !@verify_image(FORUM."attachments/".$attachname))) { unlink(FORUM."attachments/".$attachname); $error = 1; } if (!$error) { $result = dbquery("INSERT INTO ".DB_FORUM_ATTACHMENTS." (thread_id, post_id, attach_name, attach_ext, attach_size) VALUES ('".$thread_id."', '".$post_id."', '$attachname', '$attachext', '".$attach['size']."')"); } } else { @unlink($attach['tmp_name']); $error = 1; } } else { @unlink($attach['tmp_name']); $error = 2; } Member Little guy wrote: $tmp_name = $_FILES["pictures"]["tmp_name"]; $tmp_new_name = $_FILES["pictures"]["name"]; $path_parts = pathinfo($tmp_new_name); $new_name = $path_parts['filename'] . time() . $path_parts['extension']; $uploads_dir = '/uploads'; move_uploaded_file($tmp_name, "$uploads_dir/$new_name"); But I'm completely noob for coding and don't know where to put that in my forum code. Please help. Thanx in advance, sorry for longer thread, and for my english. Regards. |