PHP - Upload Large Images And Manipulate
In the past, whenever I write an image upload script in php that needs to generate a thumbnail or resized version, I have had to make sure the image is a reasonable size before uploading otherwise you get the old 'allowed memory bytes exceeded' thing.
What are my options if I want people to be able to upload a full size image from their camera i.e. a 15-20mb 4000x3000px image and then have a thumbnail and something like 500px wide version for displaying on the site? The large unaltered original needs to be stored as well as it will be used for prints. Is this just not possible with PHP? Or is it down to needing a dedicated server? Similar TutorialsHi Are there any libraries /api that allow you to upload vector files such as: AI file, TIFF or EPS and Manipulate using PHP. Operations such as changing colors, measurements etc. Any help is appreciated! I want to allow for a user to upload any photo that they might have taken from their camera. I can't get photo's with large file sizes to upload. I have changed the setting in the php5.ini and set the settings extremely high. This has always worked for me before. I also have changed the code on the form. <input type="hidden" name="MAX_FILE_SIZE" value="99000000" /> here is the code for the php5.ini register_globals = on allow_url_fopen = on expose_php = Off max_input_time = 500 variables_order = "EGPCS" extension_dir = ./ upload_tmp_dir = /tmp precision = 12 SMTP = relay-hosting.secureserver.net url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset=" [Zend] zend_extension=/usr/local/zo/ZendExtensionManager.so zend_extension=/usr/local/zo/4_3/ZendOptimizer.so register_long_arrays = on max_file_uploads = 8M post_max_size = 8M Maybe the problem is not in the php5.ini ? Hi All, Having issues uploading files larger than 1mb. This is what I have currently as default when I ran phpinfo() (working locally on my machine)... upload_max_filesize: 432M post_max_size: 432M memory_limit: 8M max_input_time: 60 max_execution_time: 30 I'm looking for the file to be converted into a blob, it works perfectly fine for files less than 1mb, but doesn't even run the mysql query above that. Any Ideas anyone? include("../../connect.php"); # these settings should help set_time_limit(0); # going in as a blob from now on $stamp = mktime(); $safename = $_FILES['Filedata']['tmp_name']; $filename = $_FILES['Filedata']['name']; $size = $_FILES['Filedata']['size']; $type = $_FILES['Filedata']['type']; $fk = $_REQUEST['fk']; $sqlname = $stamp . "-" . $_FILES['Filedata']['name']; # open and code in $fp = fopen($safename, 'r'); $content = fread($fp, filesize($safename)); $content = addslashes($content); fclose($fp); $insertS = "INSERT INTO $tableb (pal, afield, bfield, cfield, dfield, efield, ffield, ablob) VALUES ('6', '$fk', '$filename', '$size', '$type', '$width', '$height', '$content')"; $insertQ = mysql_query($insertS); print "1"; <!doctype html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <title>Untitled Document</title> </head> <body> <form action="upload_image.php" method="post" enctype="multipart/form-data"> <label>select page<input type="file" name="image"> <input type="submit" name="upload"> </label> </form> <?php if(isset($_POST['upload'])) { $image_name=$_FILES['image']['name']; //return the name ot image $image_type=$_FILES['image']['type']; //return the value of image $image_size=$_FILES['image']['size']; //return the size of image $image_tmp_name=$_FILES['image']['tmp_name'];//return the value if($image_name=='') { echo '<script type="text/javascript">alert("please select image")</script>'; exit(); } else { $ex=move_uploaded_file($image_tmp_name,"image/".$image_name); if($ex) { echo 'image upload done "<br>"'; echo $image_name.'<br>'; echo $image_size.'<br>'; echo $image_type.'<br>'; echo $image_tmp_name.'<br>'; } else { echo 'error'; } } } ?> </body> </html>I make this simple script for upload files like photo , It's work correctly ,but not upload the large files ex 8MB images 12MB images Edited by Ch0cu3r, 04 October 2014 - 09:50 AM. Modified topic title - changed download to upload Hi I am running debian lenny, apache2 php5. My fail upload fails for large file sizes. A 6.2 MB file uploads file, but a 10.2Mb file fails. I have set the Max file size to 50MB and max_execution to 600 etc in php.ini, but still have the same problems. I have noticed many others having similar problems. Is there a solution? Going to try and explain this the best I can but I don't really have the best idea on what's happening here. I have a submission form for users to fill out their information and upload an image. I've set the file limit size at 500000 which I assumed would be safe for images at 400k or below. When testing locally, any image that is below that file size gets uploaded successfully. However, when testing on my online host/server.. the submission form and data is successfully entered but the image isn't saved at all. It obviously isn't over the size of the file limit I set because it dooesn't return an error.. it successfuly submits but doesn't save or resize my image. I really have no clue what the problem could be. I went over the variables I set for folder locations to move the image to and everything works fine locally, but once on the host and online, it doesn't happen. Hello All, I have a simple upload form which I am using to upload files to Box.net using PHP Curl. It works fine for small files, but times out for larger files. Anyone have any suggestions for this? Thanks, Pete Here is the code: Code: [Select] <html> <body bgcolor="black"> <div align="center"> <img src="Homepage_02.jpg" border="0" /> <br> <br> <font color="#f1ca63"; font face="Arial"; font size="5">Upload</font> <br> <br> <?php if (isset($_POST['upload'])) { if (!empty($_FILES['new_file_1']['name'])) { $allowedExtensions = array("txt","csv","xml","css","doc", "docx","xls","xlsx","rtf","ppt","pdf","swf","flv","avi","wmv","mov","jpg","jpeg","gif","png"); foreach ($_FILES as $file) { if ($file['tmp_name'] > '') { if (!in_array(end(explode(".", strtolower($file['name']))),$allowedExtensions)) { echo $file['name'].' is an invalid file type!<br/>'; } else { $temp_name = $_FILES['new_file_1']['name']; $localfile = $_FILES['new_file_1']['tmp_name']; $file = fopen($localfile,'r'); $request_url = 'https://upload.box.net/api/1.0/upload/[Token Here]/[Folder ID]'; $post_params['check_name_conflict_folder_option'] = urlencode('1'); $post_params['new_file_1'] = "@$localfile"; $post_params['description'] = urlencode($_POST['description']); $post_params['uploader_email'] = urlencode($_POST['uploader_email']); $post_params['upload'] = urlencode('upload'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); curl_close($ch); $resultArray = explode(' ',$result); if($resultArray[5] != '') { $fileID = substr($resultArray[5],4,-1); $shareName = $temp_name; $link = 'http://www.box.net/shared/'.$shareName; } $renameurl = addslashes("https://www.box.net/api/1.0/rest?action=rename&api_key=[API KEY]&auth_token=[TOKEN Here]&target=file&target_id=".$fileID."&new_name=".$shareName); $renameResult = file_get_contents($renameurl); echo '<font color="white">Upload Successful</font>'; } } } } else { echo '<font color="white">Please select a file</font>'; } } ?> <hr width=600 color=grey> <br> <div align="center"> <form action="box_upload_curl.php" enctype="multipart/form-data" method="post"> <input type="hidden" name="check_name_conflict_folder_option" value="1"/> <table> <tr> <td class="field" style="color: #f1ca63; font-family: Arial; font-size: 14px" width="50%">Choose File to Upload: </td> <td class="input"><input type="file" name="new_file_1" /></td> </tr> <tr> <td class="field field_top" style="color: #f1ca63; font-family: Arial; font-size: 14px" ><br/> Description (optional):</td> <td class="input"><br/><textarea name="description"></textarea></td> </tr> <tr> <td class="field field_top" style="color:#f1ca63; font-family: Arial; font-size: 14px" > <br/> Your e-mail <font color="red">*</font>: </td> <td class="input field_top" style="color: #f1ca63; font-family: Arial; font-size: 14px" > <br/> <input type="text" name="uploader_email" id="email_input"></input> </td> </tr> <tr> <td colspan="2" class="submit" align="center"> <br /> <input type="submit" name="upload" value="Upload" /> </td> </tr> </table> </form> <hr width=600 color="grey"> </div> I have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett I Can't resize large images with imagecreatefromjpeg() I can load small 38kb images fine, when they get up 780+- or 1.3 mb +- (with a width of 2500px * x) I get the below error I also can upload the same pics in another file with out resizing(using imagecreatefromjpeg()) them and the script works fine. my max file upload size with xampp is 128mb / php5 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 191 extraneous bytes before marker 0xd9 in C:\xampp\htdocs\ed\phpsol\ch08\work\includes\create_thumb.inc.php on line 35 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'C:\xampp\tmp\php9596.tmp' is not a valid JPEG file in C:\xampp\htdocs\ed\phpsol\ch08\work\includes\create_thumb.inc.php on line 35 I'm basicly using a switch switch($type) { case 1: $source = @ imagecreatefromgif($original); if (!$source) { $result = 'Cannot process GIF files. Please use JPEG or PNG.'; } break; case 2: $source = imagecreatefromjpeg($original); <---- LINE 35 where $original is $original = $_FILES['image']['tmp_name']; break; I'm hoping to get a little feedback on what you all believe is the best way to handle this efficiently in PHP. I am working on a script that imports a large amount of data from remote feeds; this facilitates the quick deployment of real estate web sites, but has to download a large number of images to each new site. Assuming for right now that the bottleneck isn't in the method (fsock vs curl vs...) and that for each imported listing we're spending between .89439 and 17.0601 seconds on the image import process alone... what would you suggest for handling this over the space of 100-1000 occurrences? As of right now I have two ideas in mind, both fairly rudimentary in nature. The first idea is to shut the script down every 30-45 seconds, sleep for a second and fire off another asynchronous request to start the script again. The second idea is to fire off a new asynchronous to run the image imports separate from the main script. This would let the efficient ones clear out rather quickly while the slower imports would have their own process to run in. The only thing that worries me about this is the fact that 100 of these could be fired off every second. Even assuming half of them complete before the next round are fired off, they would still pile up. Hello... I have some simple code but no ideas for upload another image?? PHP stores image name in database but there is no second picture uploaded in the images/ folder. Pls help. Thanks if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "<strong>Slika:</strong> " . $_FILES["file"]["name"] . "<br />"; echo "<strong>Format slike:</strong> " . $_FILES["file"]["type"] . "<br />"; echo "<strong>Velicina:</strong> " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "<strong>Temp file:</strong> " . $_FILES["file"]["tmp_name"] . "<br />"; // here is mistake??? move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $_FILES["file"]["name"]); // $sql="INSERT INTO test (name, something, slika, slika2) VALUES ('".$_POST['name']."', '".$_POST['something']."', '".$_FILES['file']['name']."', '".$_FILES['slika1']['name']."')"; if (mysql_query($sql)) { echo "Sucess"; } else { echo "Error" . mysql_error(); } } } else { echo "Invalid file"; } ?> Hi there, I need a little help...
I have simple form/code for upload image and insert it into db, and its working.
<form name="unos" action="" method="post" enctype="multipart/form-data"> <select name="kategorija"> <option value="1">Album</option> </select> <input type="file" name="uploaded_file[]" id="file" > </form> <?PHP include "config.php"; $uploads_dir = 'slike'; foreach ($_FILES["uploaded_file"]["error"] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["uploaded_file"]["tmp_name"][$key]; $name = $_FILES["uploaded_file"]["name"][$key]; move_uploaded_file($tmp_name, "$uploads_dir/$name"); } } $sql="INSERT INTO galerija_slike (kategorija_id, url_slike) VALUES ('".$_POST['kategorija']."', '".$_FILES['uploaded_file']['name'][$key]."')"; if (mysql_query($sql)) { echo "success"; } else { echo "error" . mysql_error(); } ?>How can I store more image url's from input fields? When I add more input fields..... move_uploaded_file(): uploads all images, but I don't know how to also add them in db? I need something like this: <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" > <input type="file" name="uploaded_file[]" id="file" >Thanks Edited by Hrvoje, 02 February 2015 - 12:17 AM. Hi I am trying to resize images as they are uploaded. The problem I have is that the image is uploading and adding to the database, but is not resizing. The code I am using is below Code: [Select] <?php include("config.inc.php"); include('../includes/connect_inc.php'); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by add-photos.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); //resize photos to maximum height or width //define parameters - maximum height & width for new images $image_max_width=599; $image_max_height=599; $max_dimension=800; // Grab the width and height of the image. list($width,$height) = getimagesize($_FILES['photo_filename']); // If the max width input is greater than max height we base the new image off of that, otherwise we // use the max height input. // We get the other dimension by multiplying the quotient of the new width or height divided by // the old width or height. if($image_max_width > $image_max_height){ if($image_max_width > $max_dimension){ $newwidth = $max_dimension; } else { $newwidth = $image_max_width; } $newheight = ($newwidth / $width) * $height; } else { if($image_max_height > $max_dimension){ $newheight = $max_dimension; } else { $newheight = $image_max_height; } $newwidth = ($newheight / $height) * $width; } // Create temporary image file. $tmp = imagecreatetruecolor($newwidth,$newheight); // Copy the image to one with the new width and height. imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height); //end of resizing // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } header('Location: add-photos.php'); // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final </body> </html> __HTML_END; ?> Any help would be appreciated. Hi All Been desperate to crack this nut for a few years now, but seem to be failing epically! I have been building a property/real estate web site for a long time, but I have no training and have been learning as I go. I have a script written that allows me to upload data and store it in my database, what I was looking to do was add a section that allows me to upload multiple images at the same time, and store the location to another table in the same database. So what I was looking to do was remove all the...lets say rubbish to be nice...and see where it takes us. I apologize in advance for the lack of santized code...I am coding locally only, in an admin area, and will rectify before launching the site...just trying to get the bones of the script in place. Ok, first we have my form as shown here, warts and all. <?php /** * Create Listing */ ?> <div id="admin" class="intern"> <div class="banner"> <div class="logbanner">CREATE LISTING</div> </div> <div class="padding"> <form action="adminprocess.php" method="POST" enctype="multipart/form-data"> <table border="0" cellpadding="2" cellspacing="2" width="700"> <tr> <td align="right"><label class="text">Property Title: </label></td> <td><input type="text" name="property_title" maxlength="50" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Selling Agent: </label></td> <td><input type="text" name="agent" maxlength="30" value="<?php echo $session->username; ?>"></td> </tr> <tr> <td align="right"><label class="text">Style: </label></td> <td> <select id="property_type" name="property_type"> <option value="Not Selected" selected>Not Selected</option> <option value="Detached">Detached</option> <option value="Semi-Deatched">Semi-Detached</option> <option value="End Terrace">End Terrace</option> <option value="Mid Terrace">Mid Terrace</option> <option value="Flat">Flat</option> <option value="Ground Floor Flat">Ground Floor Flat</option> <option value="4 in a Block">4 in a Block</option> <option value="Bungalow">Bungalow</option> <option value="Apartment">Apartment</option> <option value="Studio">Studio</option> <option value="Maisonette">Maisonette</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Address: </label></td> <td><input type="text" name="address_one" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Address: </label></td> <td><input type="text" name="address_two" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Town: </label></td> <td><input type="text" name="town" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">County: </label></td> <td> <select id="county" name="county"> <option value="Fife" selected>Fife</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Post Code: </label></td> <td><input type="text" name="postcode" maxlength="30" value="" size="15"></td> </tr> <tr> <td align="right"><label class="text">Price: </label></td> <td> <select id="price_cond" name="price_cond"> <option value="Not Selected" selected>Not Selected</option> <option value="Offers Over">Offers Over</option> <option value="Fixed Price">Fixed Price</option> </select> <input type="text" name="price" maxlength="30" value="" size="32"> </td> </tr> <tr> <td align="right"><label class="text">Property Status: </label></td> <td> <select id="status" name="status"> <option value="Not Selected" selected>Not Selected</option> <option value="Offers Over">For Sale</option> <option value="Fixed Price">Sold Subject to Signed Missives</option> <option value="Fixed Price">Sold Subject to Survey</option> <option value="Fixed Price">Price Reduced</option> <option value="Fixed Price">Sold</option> <option value="Fixed Price">Re-Listed</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Description Header: </label></td> <td><input type="text" name="deschead" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Description: </label></td> <td><textarea cols="40" rows="8" type="text" name="desc" maxlength="1000" value=""></textarea></td> </tr> <!-- I want the images to be added here --> <tr> <td align="right"><label class="text">Reception Rooms: </label></td> <td> <select id="recrooms" name="recrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Bedrooms: </label></td> <td> <select id="bedrooms" name="bedrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Bathrooms: </label></td> <td> <select id="bathrooms" name="bathrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Garden: </label></td> <td> <select id="garden" name="garden"> <option value="Not Selected" selected>Not Selected</option> <option value="Yes">Yes</option> <option value="No">No</option> <option value="Shared">Shared</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Garage: </label></td> <td> <select id="garage" name="garage"> <option value="Not Selected" selected>Not Selected</option> <option value="Yes">Yes</option> <option value="No">No</option> <option value="Shared">Shared</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Additional Info: <br />** Not seen by site users **</label></td> <td><textarea cols="40" rows="8" type="text" name="addinfo" maxlength="1000" value=""></textarea></td> </tr> <tr> <td align="right"><label class="text"> </label></td> <td> <input type="hidden" name="subcreatelisting" value="1"> <input type="submit" value="Create Listing"> </td> </tr> </table> </form> <?php echo $form->error("creListing"); ?> </div> </div> next I have my process page which has the following function included... function procCreateListing(){ global $session, $database, $form; $q = "INSERT INTO ".TBL_PROP."(prop_id, prop_agent, prop_type, prop_add_1, prop_add_2, prop_town, prop_county, prop_pc, prop_price, prop_price_cond, prop_rec_rooms, prop_bedrooms, prop_bathrooms, prop_status, prop_garden, prop_garage, prop_description_header, prop_description, prop_add_info, prop_add_date) VALUES ('".$_POST['property_title']."', '".$_POST['agent']."', '".$_POST['property_type']."', '".$_POST['address_one']."', '".$_POST['address_two']."', '".$_POST['town']."', '".$_POST['county']."', '".$_POST['postcode']."', '".$_POST['price']."', '".$_POST['price_cond']."', '".$_POST['recrooms']."', '".$_POST['bedrooms']."', '".$_POST['bathrooms']."', '".$_POST['status']."', '".$_POST['garden']."', '".$_POST['garage']."', '".$_POST['deschead']."', '".$_POST['desc']."', '".$_POST['addinfo']."', '".$_POST['date']."')"; $database->query($q); } and I have 2 tables in mysql prop_listing and imagebin Code: [Select] CREATE TABLE `kea_userclass`.`prop_listing` ( `prop_id` INT( 10 ) NOT NULL AUTO_INCREMENT , `prop_agent` VARCHAR( 40 ) NOT NULL , `prop_type` VARCHAR( 20 ) NOT NULL , `prop_add_1` VARCHAR( 50 ) NOT NULL , `prop_add_2` VARCHAR( 50 ) NOT NULL , `prop_town` VARCHAR( 30 ) NOT NULL , `prop_county` VARCHAR( 25 ) NOT NULL , `prop_pc` VARCHAR( 8 ) NOT NULL , `prop_price` INT( 10 ) NOT NULL , `prop_price_cond` VARCHAR( 20 ) NOT NULL , `prop_rec_rooms` INT( 2 ) NOT NULL , `prop_bedrooms` INT( 3 ) NOT NULL , `prop_bathrooms` INT( 2 ) NOT NULL , `prop_status` VARCHAR( 20 ) NOT NULL , `prop_garage` INT( 1 ) NOT NULL , `prop_garden` INT( 1 ) NOT NULL , `prop_description_header` VARCHAR( 50 ) NOT NULL , `prop_description` VARCHAR( 2000 ) NOT NULL , `prop_add_info` VARCHAR( 2000 ) NOT NULL , `prop_add_date` DATE NOT NULL , PRIMARY KEY ( `prop_id` ) ) ENGINE = MYISAM ; CREATE TABLE `imagebin` ( `id` int( 11 ) NOT NULL AUTO_INCREMENT , `item_id` int( 11 ) NOT NULL , `image` varchar( 255 ) NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM DEFAULT CHARSET = latin1; first of all thanks for getting this far, I know it is a lot of reading, and a lot to ask for, but now I am stuck... I need a section on my form that would allow me to upload 8 images, and store them in a directory folder I need the location saved into my imagebin table thats it just now Many thanks for reading, and I hope someone can take me under their wing and help me passed this hurdle Hello all, I am having an issue. I have read many articles and help forums, but I cannot find a specific way to help me. My issue is this. I have a php upload form for visitors to upload an image. Now, I would like to know how to get the uploaded images to show up after the upload. Someone suggested to me to call the images. However, I am not sure how to do this. Below is the script for the image upload, which works great for uploading. <?php /* This script can send an email and/or make an entry in a log file There are two variables below - one for an email address and one for a log file Set both variables to the values you want to use If you do not want either an email or log entry, comment out the respective line For example, if you do not want an email sent, put a // in front of the $emailAddress line - same for the $logFile line */ $logFile = $_SERVER['DOCUMENT_ROOT'].'/upload.log'; // full path to your log file $emailaddress = "email@gmail.com"; $home_page = "index.html"; // used for a link to return $uploaddir = "uploads/"; // the directory where files are to be uploaded - include the trailing slash $fileTypeArray = array(".jpg",".gif",".txt"); // enter in all lower case, the script will handle a match with upper case $maxSize = 500000; // maximum file size that can be uploaded - in bytes $maxFileSpace = 50000000; // maximum space that can be used by files matching the $fileTypeArray array in the upload directory - in bytes putenv('TZ=EST5EDT'); // eastern time // change nothing below this line $maxDisplay = $maxSize / 1000; ?> <html><head></head><body> <div style="text-align: center; margin: 100px auto; border: 1px black solid; width:400px;"> <?php // print_r($_FILES); // can be used for debugging $file_name = $_FILES['file']['name']; $file_size = $_FILES['file']['size']; $file_tmp_name = $_FILES['file']['tmp_name']; if (!empty($file_name)) { unset($error); echo "<br>File Name: $file_name<br><br>"; echo "File Size: $file_size bytes<br><br>"; // file size test if ($file_size == 0 ) $error .= "<span style='color: red;'>Invalid file</span><br>"; if ($file_size > $maxSize ) $error .= "<span style='color: red;'>Your file exceeds $maxDisplay K.</span><br>"; // file type test if (!in_array(strtolower(strrchr($file_name,'.')),$fileTypeArray) ) $error .= "<span style='color: red;'>Your file is not a valid file type.</span><br>"; // max directory size test foreach(scandir($uploaddir) as $file_select) if (in_array(strtolower(strstr($file_select,'.')),$fileTypeArray)) $total_size = $total_size + filesize($uploaddir.$file_select); if (($total_size + $file_size) >= $maxFileSpace) $error .= "<span style='color: red;'>Total file space limits have been exceeded.</span><br>"; // scrub characters in the file name $file_name = stripslashes($file_name); $file_name = preg_replace("#[ ]#","_",$file_name); // change spaces to underscore $file_name = preg_replace('#[^()\.\-,\w]#','_',$file_name); //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore $file_name = preg_replace('#(_)+#','_',$file_name); //eliminate duplicate underscore // check for file already exists if (file_exists($uploaddir.$file_name)) $error .= "<span style='color: red;'>File already exists.</span><br>"; // if all is valid, do the upload if (empty($error)) { if (move_uploaded_file($file_tmp_name,$uploaddir.$file_name)) { chmod($uploaddir.$file_name,0644); echo "<span style='color: green;'>Your file was successfully uploaded!</span>"; if (isset($emailAddress)) { $message = $file_name . " was uploaded by".$_SERVER['REMOTE_ADDR']."at".date('Y-m-d H:i:s'); mail($emailaddress,"You have a file upload",$message,"From: Website <>"); } if (isset($logFile)) { $logData = $file_name."||".$_SERVER['REMOTE_ADDR']."||".date('Y-m-d H:i:s')."\r\n"; @file_put_contents($logFile,$logData,FILE_APPEND|LOCK_EX); } } else { echo "<span style='color: red;'>Your file could not be uploaded.</span>"; } } echo "$error<hr>"; } ?> <p>Upload a <span style="color: blue;"> <?php foreach($fileTypeArray as $fileType) echo $fileType; ?> </span> file to our server<br> Maximum file size is <?php echo $maxDisplay; ?>K</p> <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data"> File: <input type="file" name="file" style="width: 250px;"><br> <input type="submit" name="submit" value="Upload File"></form> <a href="<?php echo $home_page; ?>">Return to the Home Page</a> </div> What is the method or process to get the images to show up or to pull the images from the folder to a webpage? One image is displaying but when i choose image 2 it overlaps image 1..
gallery.php 8.77KB
7 downloads
I created scripting to upload multiple images simultaneously. The files sizes allowed for upload are 2 MB (or larger) and are then resized to approx 300kb each. In testing, I have discovered that the uploading terminated after 20 images. Is there a variable that needs to be re-defined in order to easily allow uploads of several hundred images? PS: I've seen several conflicting examples for defining max_file_size. What is the correct math to define this parameter? I want people to be able to post images on to my page but i want them to be able to add a caption when they post their image
This is the format I want the image and caption to be posted like
<div class="spacer"> </div> <div class="jokestary-img" title="Siri will screw up your relationship"> <img src="uploads/Siri will screw up your relationship.jpg" /> <div class="caption"><div>Siri will screw up your relationship.</div></div></div>The code for the upload form also wont work The page says "Upload complete!" before i even choose a file and doesnt send to my database ?php // properties of the uploaded file $name = $_FILES ["myfile"] ["name"]; $type = $_FILES ["myfile"] ["type"]; $size = $_FILES ["myfile"] ["size"]; $temp = $_FILES ["myfile"] ["tmp_name"]; $error= $_FILES ["myfile"] ["error"]; if ($error > 0) die ("Error uploading file! code $error."); else { if ($type== "video/av/png || $size 1000000") //conditions for file { die("That format is not allowed or file size too big"); } else move_uploaded_file($temp,"uploads/".$name); echo "Upload complete!"; } ?> Hi
I am developing a website for fun to play around with, like a little fun project and am trying to work out how to upload multiple images that stores the filename in the database and the actual file on the server
I have managed to get it working if I upload just one image but can't work it out for multiple images
Can anyone point me in the right direction or advise where I need to adjust for multiple images upload
I know on the html form on the input tag needs to have multiple and then the name in the input tag be image[] but is as far as I get, it's the PHP I get stuck on
The html for the form is below
<form action="private-add-insert.php" method="post" enctype="multipart/form-data"> Car Make: <input type="text" name="make"> Car Model: <input type="text" name="model"> Exterior Colour: <input type="text" name="exteriorcolour"> Engine Size: <input type="text" name="enginesize"> Fuel Type: <input type="text" name="fueltype"> Year Registered: <input type="text" name="yearregistered"> Transmission: <input type="text" name="transmission"> Mileage: <input type="text" name="mileage"> Number of Doors: <input type="text" name="nodoors"> Body Style: <input type="text" name="bodystyle"> Price: <input type="text" name="price"> <br> <label>Upload Images</label> <input type="file" name="image[]" multiple/> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <br /> <input type="submit" value="Submit Listing"> </form>Below is the PHP coding that processes the html form <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php // Start a session for error reporting session_start(); // Call our connection file require("includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "private-listing-images/"; // Get our POSTed variables $make = $_POST['make']; $model = $_POST['model']; $exteriorcolour = $_POST['exteriorcolour']; $enginesize = $_POST['enginesize']; $fueltype = $_POST['fueltype']; $yearregistered = $_POST['yearregistered']; $transmission = $_POST['transmission']; $mileage = $_POST['mileage']; $nodoors = $_POST['nodoors']; $bodystyle = $_POST['bodystyle']; $price = $_POST['price']; $image = $_FILES['image']; // Sanitize our inputs $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $exteriorcolour = mysql_real_escape_string($exteriorcolour); $enginesize = mysql_real_escape_string($enginesize); $fueltype = mysql_real_escape_string($fueltype); $yearregistered = mysql_real_escape_string($yearregistered); $transmission = mysql_real_escape_string($transmission); $mileage = mysql_real_escape_string($mileage); $nodoors = mysql_real_escape_string($nodoors); $bodystyle = mysql_real_escape_string($bodystyle); $price = mysql_real_escape_string($price); $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, bmp or png"; header("Location: private-add-listing.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into privatelistings (make, model, exteriorcolour, enginesize, fueltype, yearregistered, transmission, mileage, nodoors, bodystyle, price, filename) values ('$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: private-add-listing-successfully.php?msg=Listing Added successfully"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: private-add-listing.php"); exit; } ?>I know the coding needs updating to mysqli and prevent sql injections but want to get it working first and then will do them parts Thank you in advance Kind regards Ian I am trying to upload images to Imageshack directly form my site with Imageshack API, using the code bellow: index.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form action="curl-form.php" method="post" enctype='multipart/form-data'> <input type="file" id="foto" name="foto" /> <input type="submit" value="Enviar" /> </form> </body> </html> img.php <?php $data = array(); $data['fileupload'] = '@' . $_FILES["foto"]['tmp_name']; $data['key'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; $data['email'] = 'email@email.com'; $data['rembar'] = 'yes'; $data['optsize'] = '96x96'; $data['xml'] = 'yes'; $post_str = ''; foreach($data as $key=>$val) { $post_str .= $key.'='.urlencode($val).'&'; } $post_str = substr($post_str, 0, -1); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.imageshack.us/upload_api.php'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_TIMEOUT, 240); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($ch ); curl_close($ch ); if (strpos ( $response, '<' . '?xml version="1.0" encoding="iso-8859-1"?>' ) === false) { return NULL; } else { $xml = new SimpleXMLElement ( $response ); return array ( "image" => $xml->image_link, "thumb" => $xml->thumb_link ); } ?> When I upload an image, the following error occurs: "Sorry, but we've detected that unexpected data is received. Required parameter 'fileupload' is missing or your post is not multipart/form-data" What is wrong with the code? How can I send enctype='multipart/form-data' with cURL? |