PHP - Allowing Users To Upload Multiple Images, And Resize On Upload
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 Similar TutorialsThere are websites like Soundcloud, Soundclick, MySpace and more.
The Question:
How to not get a law suite as a website owner when copyright protected music or in other words music from the retail has gotten uploaded?
Will moderating it and having it frequently taken down do the job?
I know that the users themselves could get researched too. The site owner could get requested to give out IP addresses. Though, I kept this separately from that question.
I basically would be looking to be safe and not get a law suite.
I would appreciate the suggestions a lot.
My server is Linux/Apache/PHP.
When a file is uploaded, I use PHP's finfo_open to confirm that the file have the correct file extension matches and delete them if it doesn't match. I also which file mimi types and size could be uploaded.
Things I do with the files include:
Upload user's files and store them in some public directory (/var/www/html/users_public_directory/), and allow other users to directly download them.
Upload user's files and store them in some private directory (/var/www/users_private_directory/), and allow other users to download them using X-Sendfile.
Upload user's ZIP files and convert them to PDF files (unzip the ZIP file, and uses Libreoffice and Imagemagick's convert to convert them to PDFs).
From the server's prospective, what are the risks of allowing users to upload files? Are there some file types which are more dangerous to the server? Could they be executed on the server, and if so, how could this be prevented?
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!"; } ?> 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."'>"; ?> 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 Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks 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 have a form that will be used to edit various fields including images. Everything works on this form except the images. When I choose the image i want to replace and upload the new image the location of the others get erased on the MySQL database and I'm just left with the one I replaced. How can I just change the image I pick to replace without erasing the location of the others? Is there a way just to tell the script to only replace the image that corresponds with the image selected? Thank You The Form Code: [Select] <!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>FormListing </title> </head> <body>\<?php session_start(); if(empty($_SESSION['myusername'])){ // send them back to login header('location: index.php'); } $_SESSION['id']; $_SESSION['$myusername']; $id = (int)$_GET['id']; $id = substr($id, 0,5); if($id < 1 || $id > 99999) exit; $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // get value of id that sent from address bar $id=$_GET['id']; // Retrieve data from database $sql="SELECT * FROM $tbl_name WHERE id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); ?> <form method="post" action="aptmodifyform.php" enctype="multipart/form-data"/> <input type="hidden" name="id" id="id" value="<?php echo $id; ?>" /> <table width="914" height="1234" border="0"> <tr> <td width="636" height="68"><div align="right"><span style="color: #F00">*</span>Title</div></td> <td width="11"><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="title"></label> <div align="left"><span id="sprytextfield1"> <input name="title" type="text" value="<? echo $rows['title']; ?>" id="title" size="50" maxlength="50"/> </span></div></td> </tr> <tr> <td><div align="right">County</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="county"></label> <select name="county" id="county"> <option selected="selected" <?=($rows['county'] == 'Bronx') ? 'selected="selected"' : ''?>>Bronx</option> <option <?=($rows['county'] == 'Brooklyn') ? 'selected="selected"' : ''?>>Brooklyn</option> <option <?=($rows['county'] == 'Manhattan') ? 'selected="selected"' : ''?>>Manhattan</option> <option <?=($rows['county'] == 'Queens') ? 'selected="selected"' : ''?>>Queens</option> <option <?=($rows['county'] == 'Staten Island') ? 'selected="selected"' : ''?>>Staten Island</option> <option>-----------------</option> <option <?=($rows['county'] == 'Nassau') ? 'selected="selected"' : ''?>>Nassau</option> <option <?=($rows['county'] == 'Suffolk') ? 'selected="selected"' : ''?>>Suffolk</option> </select></td> </tr> <tr> <td><div align="right">Town</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="town"></label> <input name="town" type="text" value="<? echo $rows['town']; ?>" id="town" size="50" maxlength="30"/></td> </tr> <tr> <td><div align="right">Description<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </div></td> <td><div align="center"> <p>:<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </p> </div></td> <td colspan="3" style="text-align: left"><label for="description"></label> <textarea name="description" cols="70" rows="25" id="description"><?php echo $rows['description']; ?></textarea></td> </tr> <tr> <td style="text-align: right; color: #000;">Service</td> <td style="text-align: center">:</td> <td colspan="3" style="text-align: left"><label for="service"></label> <select name="service" size="1" id="service"> <option <?=($rows['service'] == 'Landlord') ? 'selected="selected"' : ''?>>Lanlord</option> <option <?=($rows['service'] == 'Property Mangement') ? 'selected="selected"' : ''?>>Property Mangement</option> <option <?=($rows['service'] == 'Realtor') ? 'selected="selected"' : ''?>>Realtor</option> </select></td> </tr> <tr> <td><div align="right">Service Fees</div></td> <td>:</td> <td colspan="3" style="text-align: left"><select name="feeornofee" id="feeornofee"> <option <?=($rows['feeornofee'] == 'Broker Fees + Other Fees') ? 'selected="selected"' : ''?>>Broker Fees + Other Fees</option> <option <?=($rows['feeornofee'] == 'Broker Fees') ? 'selected="selected"' : ''?>>Broker Fees</option> <option <?=($rows['feeornofee'] == 'Other Fees - No Broker Fee') ? 'selected="selected"' : ''?>>Other Fees - No Broker Fee</option> <option <?=($rows['feeornofee'] == 'No Fees') ? 'selected="selected"' : ''?>>No Fees</option> </select></td> </tr> <tr> <td><div align="right">Lease Type</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="lease"></label> <select name="lease" id="lease"> <option <?=($rows['lease'] == 'Rent Stabilized ') ? 'selected="selected"' : ''?>>Rent Stabilized </option> <option <?=($rows['lease'] == 'Prime, non-stabilized lease') ? 'selected="selected"' : ''?>>Prime, non-stabilized lease</option> <option <?=($rows['lease'] == 'Coop (sub) Lease') ? 'selected="selected"' : ''?>>Coop (sub) Lease</option> <option <?=($rows['lease'] == 'Condo Lease') ? 'selected="selected"' : ''?>>Condo Lease</option> <option <?=($rows['lease'] == 'Commercial Lease') ? 'selected="selected"' : ''?>>Commercial Lease</option> <option <?=($rows['lease'] == 'Other') ? 'selected="selected"' : ''?>>Other</option> </select></td> </tr> > <tr> <td><div align="right">Contact's Name</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="contact"></label> <input name="contact" type="text" value="<? echo $rows['contact']; ?>" id="contact" size="40" maxlength="40" /></td> </tr> <tr> <td><div align="right">Name of Office</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="office"></label> <input name="office" type="text" value="<? echo $rows['office']; ?>" id="office" size="40" maxlength="40" /></td> </tr> <tr> <td><div align="right">Pets</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="pets"></label> <select name="pets" id="pets"> <option <?=($rows['pets'] == 'Pets Allowed') ? 'selected="selected"' : ''?>>Pets Allowed</option> <option <?=($rows['pets'] == 'No Pets') ? 'selected="selected"' : ''?>>No Pets</option> <option <?=($rows['pets'] == 'Pets Allowed - Small pets') ? 'selected="selected"' : ''?>>Pets Allowed - Small pets</option> </select></td> </tr> <tr> <td><div align="right">Phone<br /> </div> <br /></td> <td><div align="center">:<br /> <br /> </div></td> <td colspan="3" style="text-align: left"><label for="phone"></label> <span id="rental_phone"> <input type="text" name="phone" value="<? echo $rows['phone']; ?>"id="phone" /> <span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span><br /> <span style="font-style: italic; font-size: 14px; font-weight: bold;">ex. (123) 456-7890 - Please keep this format.</span></td> </tr> <tr> <td style="text-align: right"><p>Location<br /> </p> <p><br /> <br /> <br /> </p></td> <td style="text-align: center">:<br /> <br /> <br /> <br /> <br /></td> <td colspan="3" style="text-align: left"><label for="cross_streets"></label> <input name="cross_streets" type="text" value="<? echo $rows['cross_streets']; ?>" id="cross_streets" size="80" maxlength="100" /> <br /> <span style="color: #F00">Please insert here the intersecting streets. Make sure you add the word "and" <br /> between streets <br /> OR<br /> You can put the property's full address. <br /> e.g. 193rd Street AND Jamaica Avenue, Jamaica, NY </span></td> </tr> <tr> <td style="text-align: right">Zip Code</td> <td style="text-align: center">:</td> <td colspan="3" style="text-align: left"><input name="zipcode" type="text" id="zipcode" value="<? echo $rows['zipcode']; ?>" size="9" maxlength="5" /></td> </tr> <tr> <td style="text-align: right"><span style="color: #000">Email </span><br /> <br /></td> <td style="text-align: center">:<br /> <br /></td> <td colspan="3" style="text-align: left"><label for="email"></label> <input name="email" type="text" value="<? echo $rows['email']; ?>" id="email" size="60" maxlength="60" /> <br /> <span style="font-size: 12px; font-style: italic;">This field is optional. It will be viewable to users.</span></td> </tr> <tr> <td><div align="right">Rooms</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="rooms"></label> <select name="rooms" id="rooms"> <option <?=($rows['rooms'] == '0') ? 'selected="selected"' : ''?>>0</option> <option <?=($rows['rooms'] == '1') ? 'selected="selected"' : ''?>>1</option> <option <?=($rows['rooms'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option> <option <?=($rows['rooms'] == '2') ? 'selected="selected"' : ''?>>2</option> <option <?=($rows['rooms'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option> <option <?=($rows['rooms'] == '3') ? 'selected="selected"' : ''?>>3</option> <option <?=($rows['rooms'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option> <option <?=($rows['rooms'] == '4') ? 'selected="selected"' : ''?>>4</option> <option <?=($rows['rooms'] == '4.5') ? 'selected="selected"' : ''?>>4.5</option> <option <?=($rows['rooms'] == '5') ? 'selected="selected"' : ''?>>5</option> <option <?=($rows['rooms'] == '5.5') ? 'selected="selected"' : ''?>>5.5</option> <option <?=($rows['rooms'] == '6') ? 'selected="selected"' : ''?>>6</option> </select> 0 = Studio, 1 = 1 Bedroom, etc.</td> </tr> <tr> <td><div align="right">Bath</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="bath"></label> <select name="bath" id="bath"> <option <?=($rows['bath'] == '0') ? 'selected="selected"' : ''?>>0</option> <option <?=($rows['bath'] == '1') ? 'selected="selected"' : ''?>>1</option> <option <?=($rows['bath'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option> <option <?=($rows['bath'] == '2') ? 'selected="selected"' : ''?>>2</option> <option <?=($rows['bath'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option> <option <?=($rows['bath'] == '3') ? 'selected="selected"' : ''?>>3</option> <option <?=($rows['bath'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option> <option <?=($rows['bath'] == '4') ? 'selected="selected"' : ''?>>4</option> </select></td> </tr> <tr> <td><div align="right">Square ft.</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="square"></label> <input name="square" type="text" value="<? echo $rows['square']; ?>" id="square" size="6" maxlength="6" /></td> </tr> <tr> <td><div align="right"><span style="color: #F00">*</span>Rent</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="rent"> $ <input name="rent" type="text" value="<? echo $rows['rent']; ?>" id="rent" size="10" maxlength="10" /> </label></td> </tr> <tr> <td><div align="right"><span style="color: #F00">*</span>Fees </div></td> <td><div align="center"> <p>: </p> </div></td> <td colspan="3" style="text-align: left"><label for="fees"></label> <span id="sprytextfield3"> <input name="fees" type="text" id="fees" value="<? echo $rows['fees']; ?>" size="90" /> </span></td> </tr> <tr> <td colspan="5" style="text-align: center; font-weight: bold; font-size: 18px; color: #F00;"> Video Link</td> </tr> <tr> <td><div align="right">URL</div></td> <td><div align="center">:</div></td> <td colspan="3"><p> </p> <p> <input name="url" type="text" id="url" value="<? echo $rows['url']; ?>"size="80" /> </td> </tr> <tr> <td><div align="center" style="color: #F00"> <div align="right">Name Your Video Link</div> </div></td> <td><div align="center"> <p>: </p> </div></td> <td colspan="3"><br /> <p> <input name="videotitle" type="text" id="videotitle" value="<? echo $rows['videotitle']; ?>"size="80" /> <br /> <span style="color: #E62E00">If you posted a URL for your video you must give it a title to give it a link.</span></p></td> </tr> <tr> <td colspan="2" style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl1']; ?>" width="200" /><br /></td> <td width="213" style="text-align: center"><img src="<? echo $rows['imageurl2']; ?>" width="200" /></td> <td width="180" style="text-align: center"><img src="<? echo $rows['imageurl3']; ?>" width="200" /></td> <td width="188" style="text-align: center"><img src="<? echo $rows['imageurl4']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><div align="center"> <input id="image3" type="file" name="image1" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image3" type="file" name="image2" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image3" type="file" name="image3" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image4" type="file" name="image4" /> </div></td> </tr> <tr> <td colspan="5" style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl5']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl6']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl7']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl8']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><input id="image5" type="file" name="image5" /></td> <td style="text-align: center"><input id="image6" type="file" name="image6" /></td> <td style="text-align: center"><input id="image7" type="file" name="image7" /></td> <td style="text-align: center"><input id="image8" type="file" name="image8" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl9']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl10']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl11']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl12']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><input id="image9" type="file" name="image9" /></td> <td style="text-align: center"><input id="image10" type="file" name="image10" /></td> <td style="text-align: center"><input id="image11" type="file" name="image11" /></td> <td style="text-align: center"><input id="image12" type="file" name="image12" /></td> </tr> <tr> <td colspan="5" style="text-align: center"> </td> </tr> <tr> <td colspan="5" style="text-align: center"><span style="color: #F00">*</span> REQUIRED FIELDS </td> </tr> <tr> <td colspan="5" style="text-align: center"> PRESS SUBMIT ONCE!!!</td> </tr> <tr> <td colspan="5" style="text-align: center"><input type="submit" name="button" id="button" value="Submit Changes" /> <input type="reset" name="button" id="button" value="Reset" /></td> </tr> </table> </form> </body> </html> The Script Code: [Select] <?php session_start(); include('SimpleImage.php'); $image = new SimpleImage(); //error_reporting(E_ALL); // image upload folder $image_folder = 'images/classified/'; // fieldnames in form $all_file_fields = array('image1', 'image2' ,'image3', 'image4', 'image5', 'image6', 'image7', 'image8', 'image9', 'image10', 'image11', 'image12'); // allowed filetypes $file_types = array('jpg','gif','png'); // max filesize 5mb $max_size = 5000000; //echo'<pre>';print_r($_FILES);exit; $time = time(); $count = 1; foreach($all_file_fields as $fieldname){ if($_FILES[$fieldname]['name'] != ''){ $type = substr($_FILES[$fieldname]['name'], -3, 3); // check filetype if(in_array(strtolower($type), $file_types)){ //check filesize if($_FILES[$fieldname]['size']>$max_size){ $error = "File too big. Max filesize is ".$max_size." MB"; }else{ // new filename $filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type; // move/upload file $image->load($_FILES[$fieldname]['tmp_name']); if($image->getWidth() > 150) { //if the image is larger that 150. $image->resizeToWidth(500); //resize to 500. } $target_path = $image_folder.basename($filename); //image path. $image->save($target_path); //save image to a directory. //save array with filenames $images[$count] = $image_folder.$filename; $count = $count+1; }//end if }else{ $error = "Please use jpg, gif, png files"; }//end if }//end if }//end foreach if($error != ''){ echo $error; }else{ //error_reporting(E_ALL); //ini_set('display_errors','On'); $id = $_POST['id']; $id = substr($id, 0,5); if($id < 1 || $id > 99999) exit; $servername = "localhost"; $username = ""; $password = ""; if(!$_POST["title"] || !$_POST["rent"] || !$_POST["fees"]){ header('location: fields.php'); }else if (!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["rent"])))){ header('location: rent.php'); }else{ $conn = mysql_connect($servername,$username,$password)or die(mysql_error()); mysql_select_db("genesis_apts",$conn); // validate id belongs to user $sql_check = "SELECT * FROM apartments WHERE id = '".$id."' AND username = '".$myusername."'"; $res = mysql_query($sql_check,$conn) or die(mysql_error()); $count = mysql_num_rows($res); if ($count > 0){ $sql = "UPDATE apartments SET title = '".mysql_real_escape_string($_POST['title'])."', description = '".mysql_real_escape_string($_POST['description'])."', cross_streets = '".mysql_real_escape_string($_POST['cross_streets'])."', county = '".mysql_real_escape_string($_POST['county'])."', town = '".mysql_real_escape_string($_POST['town'])."', service = '".mysql_real_escape_string($_POST['service'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', contact = '".mysql_real_escape_string($_POST['contact'])."', office = '".mysql_real_escape_string($_POST['office'])."', pets = '".mysql_real_escape_string($_POST['pets'])."', email = '".mysql_real_escape_string($_POST['email'])."', rooms = '".mysql_real_escape_string($_POST['rooms'])."', bath = '".mysql_real_escape_string($_POST['bath'])."', square = '".mysql_real_escape_string($_POST['square'])."', rent = '".mysql_real_escape_string($_POST['rent'])."', fees = '".mysql_real_escape_string($_POST['fees'])."', service = '".mysql_real_escape_string($_POST['service'])."', feeornofee = '".mysql_real_escape_string($_POST['feeornofee'])."', lease = '".mysql_real_escape_string($_POST['lease'])."', url = '".mysql_real_escape_string($_POST['url'])."', zipcode = '".mysql_real_escape_string($_POST['zipcode'])."', videotitle = '".mysql_real_escape_string($_POST['videotitle'])."', imageurl1 = '".mysql_real_escape_string($images[1])."', imageurl2 = '".mysql_real_escape_string($images[2])."', imageurl3 = '".mysql_real_escape_string($images[3])."', imageurl4 ='".mysql_real_escape_string($images[4])."', imageurl5 = '".mysql_real_escape_string($images[5])."', imageurl6 = '".mysql_real_escape_string($images[6])."', imageurl7 = '".mysql_real_escape_string($images[7])."', imageurl8 = '".mysql_real_escape_string($images[8])."', imageurl9 = '".mysql_real_escape_string($images[9])."', imageurl10 = '".mysql_real_escape_string($images[10])."', imageurl11 = '".mysql_real_escape_string($images[11])."', imageurl12 = '".mysql_real_escape_string($images[12])."' WHERE id = '".$id."'"; //replace info with the table name above $result = mysql_query($sql,$conn) or die(mysql_error()); header('location: apartments.php'); }else{ header('location: wrong.php'); } } } ?> 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've looked around at a bunch of sample code and cannot seem to get this to work. I'm trying to create a table with the values provided in a form along with an uploaded image. Here is what I have. Code: [Select] <?php //Set variables from form $title = $_POST["title_textfield"]; $description = $_POST["description_textbox"]; $price = $_POST["price_textfield"]; $time = date("ymdHis"); $me = $myuserID /Create Table $con = mysql_connect("mydatabase.mysql.com","databaseAdmin","Adminpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } //check if table exists // Create table $time = date("ymdHis"); $tablename = "1_$me$time"; mysql_select_db("db_01", $con); $sql = "CREATE TABLE $tablename ( ID int NOT NULL AUTO_INCREMENT, imageData LONGBLOB NOT NULL , PRIMARY KEY(comicID), Owner varchar(15), Status varchar(15), AgeRestriction varchar(25), Title varchar(25), Description varchar(100), Price varchar(15) )"; // Execute query mysql_query($sql,$con); //input info into table mysql_query("INSERT INTO $tablename (Owner, Status, Title, Description, Price) VALUES ('$myid', 'Pending', '$title', '$description', '$price')"); //Image control!!!! $maxFileSize = "2000000"; // 2 MB file size //Initializing the image types. $image_array = array("image/jpeg","image/jpg","image/gif","image/bmp","image/pjpeg","image/png"); // valid image type //store the file type of the uploading file. $fileType = $_FILES['userfile']['type']; $nname= $_FILES['userfile']['name']; echo "$nname"; //Initializing the msg variable. Although , not necessary. $msg = ""; // if Submit button is clicked if(@$_POST['Submit']) { // check for the image type , before uploading if (in_array($fileType, $image_array)) { // check whether the file is uploaded if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check whether the file size is below 2 mb if($_FILES['userfile']['size'] < $maxFileSize) { // reading the image data $imageData =addslashes (file_get_contents($_FILES['userfile']['tmp_name'])); // inserting into the database $sql = "INSERT INTO $tablename (imageData) VALUES ('$imageData')"; mysql_query($sql) or die(mysql_error()); $msg = " Data successfully uploaded"; } else { $msg = " Error : File size exceeds the maximum limit "; } } } else { $msg = "Error: Not a valid image "; } } mysql_close($con); ?> All the fields populate just fine except the imageData field which shows "[BLOB - 0 Bytes]" Any help would be GREATLY appreciated. Thank you for even taking the time to look. Cordially, TcS When i use the following script to upload and resize an image, it throws out errors (see after script) <?php $image = $_FILES['image']['name']; $uploaddir = "./images/$gender/"; $pext = getExtension($image); $pext = strtolower($pext); if (($pext != "jpg") && ($pext != "jpeg") && ($pext != "gif")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only an image with the extension .jpg or .jpeg or .gif ONLY<br><br>"; print "The file you uploaded had the following extension: $pext</p>\n"; unlink($imgfile); exit(); } $imgsize = GetImageSize($image); /*== check size 0=width, 1=height ==*/ if (($imgsize[0] > 460) || ($imgsize[1] > 345)) { $tmpimg = tempnam("/tmp", "MKUP"); system("djpeg $image >$tmpimg"); system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile"); unlink($tmpimg); } $rand = rand(0,9999999); $date = DATE("d.m.y"); $image_name=$date.$id.$rand.'.'.$extension; $final_filename = str_replace(" ", "_", $image_name); $newfile = $uploaddir . "/$final_filename"; if (is_uploaded_file($image)) { if (!copy($imgfile,"$newfile")) { print "Error Uploading File."; exit(); } } unlink($image); print("<img src=\"$newfile\">"); ?> errors: Quote Warning: getimagesize((R)Photo-0027.jpg) [function.getimagesize]: failed to open stream: No such file or directory in /home/bumwarsc/public_html/images.php on line 77 Warning: unlink((R)Photo-0027.jpg) [function.unlink]: No such file or directory in /home/bumwarsc/public_html/images.php on line 126 I am having a lot of trouble finding material to help me with this problem. I am using cakephp 1.2. What i want to be able to do is give users the ability to upload an avatar. For form is quite basic (takes the data and updates the corresponding record in the database) but I need to add in a file upload form object so the user can pick an image then i my code to be able to take that image and save it in multiple sizes and finally to save the image name and extension (ex: image.jpg) in to the database table. If anyone can help me with this it would be such a massive help. What I want to do is to upload an image, find out what the size is and then make the height=377, and keep with width at the same ratio. this is my upload code: Code: [Select] <?php error_reporting(0); mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("myDB") or die(mysql_error()); $picture = $_FILES['image']['tmp_name']; $brand = $det['pro_name']; $year = $det['pro_vint']; $story = $det['pro_story']; $description = $det['pro_desc']; $why = $det['pro_why']; $intensity = $det['F12']; $body = $det['F11']; $sweet = $det['F8']; $acid = $det['F9']; $oak = $det['F10']; $lcbo = $det['lcbo_num']; $size = $det['pro_size']; $btl = $det['pro_btl']; $price = $det['pro_price']; $lto = $det['F7']; $audio = $det['wineAudio']; if(!isset($picture)) echo ""; else { $image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); $image_name = addslashes($_FILES['image']['name']); $image_size = getimagesize($_FILES['image']['tmp_name']); list($width, $height, $type, $attr) = getimagesize($_FILES['image']['tmp_name']); if($height != $width * 1.5 ){ echo "Image does not meet requirements"; }else{ if($image_size==FALSE) echo "This is not an Image"; else{ if(!$insert = mysql_query ("UPDATE `phpmy1_vincastweb_com`.`Sheet1` SET `image_name` = '".$image_name."', image='".$image."' WHERE `pro_id` ='".$id."'")) echo "Problem Uploading Image."; else{ $lastid = mysql_insert_id(); echo "Image Uploaded!<p />".$text."<p /><p /> Your Image:<p />"; $lastid = $id; echo "<img src='get_2.php?Product=$lastid' width='250' height='320' /><br />Click <a href='Agency/product3.php?Product=".$id."' target='_blank'>HERE</a> to view with Product" ; } } } } ?> right now I have it so that its at a ratio of height=3, and width=2...everything works fine but its not exactly what i want.. any ideas ? Hi! I'm looking for a script that can do the following: upload one or preferably fx. five image files(jpg) resizes them to a specific size if they exceeds that size. create a thumbnail No files above 100kb can be uploaded. uploaded and/or processed files must be renamed with a unique file name. Work with php5 I have searched the internet for a script like that, but I can't find one that matches my needs. Also, the code must include good comments and nott be to hard to understand. So as basic code as possible. Hello, How could I resize the image to 320x480 before it is uploaded. Here is the code for the upload: Code: [Select] <?php require("connect.php"); $query = mysql_query("SELECT * FROM items ORDER BY id DESC"); if (mysql_num_rows($query) > 0) { $row = mysql_fetch_assoc($query); $id = $row['id']; $id++; echo $id."<br>"; $username = $_GET['user']; $dateofupload = date("Y-m-d"); $uploaddir = './pqimages/'.$dateofupload.'/'; $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir.$id.".jpg"; if (move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)){ echo "http://randomaydesigns.com/pqimages/{$file}"; $userid = mysql_query("SELECT * FROM users WHERE username ='$username'"); while ($row2 = mysql_fetch_assoc($userid)){ $userid = $row2['id']; $updateuserlastupload = mysql_query("UPDATE users SET lastupload='pqimages/".$dateofupload."/$id.jpg' WHERE username='$username'"); $updateuser = mysql_query("INSERT INTO items VALUES('','$userid','1','i','','','pqimages/".$dateofupload."/$id.jpg','0','a','$dateofupload')"); } } } ?>Cheers, GEORGE Alright guys, i have been looking for a simple script for this online to try get my head around it. I need a script thats is going to take an image and save the orginal file along with two modified files (small and medium thumbnail). I really cant get my head around the ones i have already seen so i was wondering if anyone had any advice or a link they can post me to that can help me. I am using cakephp and i need a quick simple image upload and re-size script, can any one help? Hi guys, Im trying to resize and create thiumbnails while uploading an image but it doesnt work, as i am new to php and i have followed other tutorials, i might have made a mistake which i dont understand. i have a table called test (find attached image) and what i need is when i upload an image, it copies the location of both image and on fly created thumb into my database i appreciate your help & please excuse me for messed up code <?php session_start(); include ("../global.php"); //welcome messaage echo "Welcome, " .$_SESSION['username']."!<p>"; $username=$_SESSION['username']; //get user id & credit limit $query=mysql_query("SELECT id FROM users"); while($row = mysql_fetch_array($query)) { $id = $row['id']; echo $id; } $credit=mysql_query("SELECT credit FROM users"); while($row = mysql_fetch_array($credit)) { $creditcheck = $row['credit']; echo "your credit is: $creditcheck"; } $reference = rand(11111111,99999999); //image1 define ("MAX_SIZE","100"); define ("WIDTH","150"); define ("HEIGHT","100"); function make_thumb($img_nameone,$filenameone,$new_w,$new_h) { $ext=getExtension($img_nameone); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_imgone=imagecreatefromjpeg($img_nameone); if(!strcmp("png",$ext)) $src_imgone=imagecreatefrompng($img_nameone); $old_x=imageSX($src_imgone); $old_y=imageSY($src_imgone); $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; } $dst_imgone=ImageCreateTrueColor($thumb_w,$thumb_h); imagecopyresampled($dst_imgone,$src_imgone,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); if(!strcmp("png",$ext)) imagepng($dst_imgone,$filenameone); else imagejpeg($dst_imgone,$filenameone); imagedestroy($dst_imgone); imagedestroy($src_imgone); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if ($creditcheck<=0) Header("Location: buy-credit.php"); else if ($creditcheck>=0){ if(isset($_POST['register'])) $submit = mysql_query("INSERT INTO test (reference) VALUES ('$reference')"); { $image=$_FILES['myfileone']['nameone']; if ($image) { $filename = stripslashes($_FILES['myfileone']['nameone']); $extension = getExtension($filenameone); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { $size=getimagesize($_FILES['myfileone']['tmp_name']); $sizekb=filesize($_FILES['myfileone']['tmp_name']); if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } $image_nameone=time().'.'.$extension; $newname="rentimages/".$image_nameone; $copied = copy($_FILES['myfileone']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { $thumb_name='rentimages/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} if(isset($_POST['register']) && !$errors) { $locationone="rentimages/$nameone"; $image1 = mysql_query ("UPDATE test SET image1='$newname', thumb='$thumb_name' WHERE reference='$referenceran'"); } } } ?> <html> <body> <form action='imagetests.php' method='POST' enctype='multipart/form-data'> File: <input type='file' name='myfileone'><p /> <input type='submit' name='register' value='Update'> <p /> </body> </html> Okay, so I found this code on-line that uploads images via a form, inserts them in to MySQL and displays the images on the page. It works great! Problem is, I spent a long time hacking this script to make it work with my site just to realize it did not re-size the image after it uploaded (dumb me). I have found other code that do this but I really do not want to start over at this point and my level of expertise with PHP are a step below what I need to figure this out. I am attaching the "original" code. If anyone knows how to add the necessary lines of code to make every image re-size (reduce) itself. I would very much appreciate it. Thanks <?php $con=mysql_connect("localhost", "root", "rootwdp")or die("cannot connect"); mysql_select_db("student",$con)or die("cannot select DB"); if(isset($_POST['upload'])) { $img=$_FILES["image"]["name"]; foreach($img as $key => $value) { $name=$_FILES["image"]["name"][$key] ; $tname=$_FILES["image"]["tmp_name"][$key]; $size=$_FILES["image"]["size"][$key]; $oext=getExtention($name); $ext=strtolower($oext); $base_name=getBaseName($name); if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){ if($size< 1024*1024){ if(file_exists("upload/".$name)){ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'"; $res=mysql_fetch_array(mysql_query($qry)); $id=$res['id']; $qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id"; mysql_query($qry); echo "Image '$name' updated<br />"; } else{ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');"; mysql_query($qry); echo "Image '$name' uploaded<br />"; } } else{ echo "Image size excedded.<br />File size should be less than 1Mb<br />"; } } else{ echo "Invalid file extention '.$oext'<br />"; } } } function getExtention($image_name){ return substr($image_name,strrpos($image_name,'.')+1); } function getBaseName($image_name){ return substr($image_name,0,strrpos($image_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> <script type="text/javascript"> function addItems() { var table1 = document.getElementById('tab1'); var newrow = document.createElement("tr"); var newcol = document.createElement("td"); var input = document.createElement("input"); input.type="file"; input.name="image[]"; newcol.appendChild(input); newrow.appendChild(newcol); table1.appendChild(newrow); } function remItems() { var table1 = document.getElementById('tab1'); var lastRow = table1.rows.length; if(lastRow>=2) table1.deleteRow(lastRow-1); } </script> <style type="text/css"> <a class="tooltip" and them url href="/http.www.anyurl.com" </a> a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;} a.tooltip span {display:none; padding:2px 3px; margin-left:8px; width:150px;} </style> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <table align="center" border="0" id="tab1"> <tr> <td width="218" align="center"><input type="file" name="image[]" /></td> <td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td> <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td> </tr> </table> <table align="center" border="0" id="tab2"> <tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr> </table> </form> <table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center"> <iframe style="display:none" name="if1" id="if1"></iframe> <? $qry="select * from img where img_status='Y' order by id"; $res=mysql_query($qry); $i=0; if(mysql_num_rows($res)){ ?> <div align="center"><ul style="width:650px; border: 0px"> <? while($fetch=mysql_fetch_array($res)){ $hratio=120/$fetch['img_height']; $wratio=120/$fetch['img_width']; $ratio=($hratio < $wratio) ? $hratio : $wratio; $hth=$fetch['img_height']*$ratio; $wth=$fetch['img_width']*$ratio; ?> <li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br /> <? if($i==0) $fp=fopen("fileInfo.txt",'w'); else $fp=fopen("fileInfo.txt",'a'); fwrite($fp,"Image : ".++$i ."\r\n"); fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n"); fwrite($fp,"width X height : ".$fetch['img_width']." X ".$fetch['img_height']."\r\n"); fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n"); fwrite($fp,"____________________________________\r\n"); fclose($fp); echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />'; echo $fetch['img_width'].' X '; echo $fetch['img_height'].'<br />'; echo round($fetch['size']/1024,1) .'Kb'; ?> </li> <? }?> </ul> </div><? }?> </td></tr></table> </body> </html> |