PHP - Multiple Upload Script Not Working
Hello Everyone,
I have been working on this add product script but cannot seem to get it to work when two files are uploaded. All the data is uploaded to a database, including the two images filenames and then the two files are added to the server to different locations. Here is the form: <form action="addnewproduct.php" method="post" name="addproduct" id="addproduct" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="10000000"> <table width="98%" border="0" cellspacing="0" cellpadding="5"> <tr> <td width="28%" valign="middle" class="style1 style2"><div align="right" class="style5">Product Title </div></td> <td width="72%" class="style5"><input class="form" type="text" name="title" accesskey="1" tabindex="1" /></td> </tr> <tr> <td valign="middle" class="style1 style2"><div align="right" class="style5">Category</div></td> <td class="style5"> <select class="form" name="cat" accesskey="2" tabindex="2"> <option value="Boards">Boards</option> <option value="Accessories">Accessories</option> <option value="Clothing">Clothing</option> </select> </td> </tr> <tr> <td valign="top" class="style5"><div align="right">Description</div></td> <td class="style5"><textarea class="form" name="description" cols="50" rows="5" accesskey="3" tabindex="3"></textarea></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Price<br /> <span class="d">Including </span></div></td> <td class="style5"><input class="form" type="text" name="price" accesskey="4" tabindex="4" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Paypal Link<br /> <span class="d">Including</span></div></td> <td class="style5"><input class="form" type="text" name="paypal" accesskey="5" tabindex="5" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Thumbnail<br /> <span class="d">Image should be 100 x 100 </span></div></td> <td class="style5"> <input style="padding:2px; border:1px #999 solid; color:blue;" name="userfile[]" type="file" id="userfile[]"> </td> </tr> <tr> <td valign="top" class="style5"><div align="right">Image<br /> <span class="d">Image should be 300 x 450 </span></div></td> <td class="style5"><input style="padding:2px; border:1px #999 solid; color:blue;" name="userfile[]" type="file" id="userfile[]" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right"></div></td> <td class="style5"><input class="form" type="submit" name="upload" value="upload" accesskey="6" tabindex="6" /></td> </tr> </table> </form> And here is the script: <?php $uploadDir = 'upload/'; $uploadDir2= "upload/big".$HTTP_POST_FILES['userfile']['name'][1]; copy($HTTP_POST_FILES['userfile']['tmp_name'][1], $uploadDir2); if(isset($_POST['upload'])) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $largeimage = $_FILES['userfile']['name'][1]; $filePath = $uploadDir . $fileName; $result = move_uploaded_file($tmpName, $filePath); if (!$result) { echo "Error uploading file"; exit; } include 'config.php'; include 'opendb.php'; if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); $largeimage = addslashes($largeimage); } $query = "INSERT INTO Products (title, description, price, paypal, cat, image, large) ". "VALUES ('$_POST[title]','$_POST[description]','$_POST[price]','$_POST[paypal]','$_POST[cat]','$fileName','$largeimage')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); include 'closedb.php'; echo 'Product Uploaded'; ?> Similar TutorialsHi 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'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 Not sure if this is the right forum, but I have a database that I will need to populate with a large number of rows (2000+). I have written a PHP script that uploads individual entries. Is it possible to use something like a spreadsheet where I can set out the rows/columns as they will appear in the database, and then upload in one go rather than uploading each row individually? Thanks for any observations and/or help. Hi all, I am having a few problems. Basically I have a multiple file upload script, that I can get successfully to save the images to a folder. However what I am trying to do is enter a record in the database for every file that is uploaded, giving it a picture id, album id and user id (p_id, a_id, u_id). From here I then want to rename the image to the p_id in the database(auto_increment). I am starting just by counting the amount of images uploaded and then creating a record. However I seem to have something wrong, as when I tried it to upload 1 image as a test it created 388,000 blank records! (just p_id as auto) Can someone explain what I am doing wrong? I am quite new to php. <?php $result = array(); $result['time'] = date('r'); $result['addr'] = substr_replace(gethostbyaddr($_SERVER['REMOTE_ADDR']), '******', 0, 6); $result['agent'] = $_SERVER['HTTP_USER_AGENT']; if (count($_GET)) { $result['get'] = $_GET; } if (count($_POST)) { $result['post'] = $_POST; } if (count($_FILES)) { $result['files'] = $_FILES; } // we kill an old file to keep the size small if (file_exists('script.log') && filesize('script.log') > 102400) { unlink('script.log'); } $log = @fopen('script.log', 'a'); if ($log) { fputs($log, print_r($result, true) . "\n---\n"); fclose($log); } // Validation $error = false; if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) { $error = 'Invalid Upload'; } else { include('../includes/config.php'); session_start(); $a_id = $_SESSION["a_id"]; $u_id = $_SESSION["id"]; $togo = $result['files']; $i=0; while ($i < $togo) { $query = mysql_query("INSERT into images (a_id,u_id) VALUES ('$a_id','$u_id')"); $i++; } } ?> Many Thanks Hi all, As you will see this is my first post in I really hope somebody can nail this for me, as I have been working on this for some time and I cannot get it to work. Basically this is the final part of a CMS I'm building, and all was fine until I needed to build in an option of a multiple image uploader to accompany all other stock details. I have managed to nail the 'insert' part of the multiple image uploader in this case up to 4 images, and the code is below for this part, any help with improvements though will be greatly appreciated. Code: [Select] if(isset($_POST['btnsubmit'])) { $flag=$_POST['flag']; if ($flag==0) { $name=$_POST['txtname']; $desc1=$_POST['e1m1']; $meta=$_POST['txtmeta']; $sr=$_POST['srno1']; $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $str_str=''; $p=''; $j=0; for($i=0;$i<=3;$i++){ $j++; $p=$_REQUEST['p$j']; $file=$_FILES['pic']['name'][$i]; if(!empty($file) ){ $str_str.=",pic$j='$file'"; } else if(!empty($p))$str_str.=",pic$j='$p'"; $path1="imgdata/stock/".$file; copy($_FILES['pic']['tmp_name'][$i], $path1); } $q24=mysql_query("update stock set stock_Name='$name', stock_MetaTitle='$meta', parent_Category='$pcats', sub_Category='$subcats', stock_Image='imgdata/stock/$pic[0]', stock_Image2='imgdata/stock/$pic[1]', stock_Image3='imgdata/stock/$pic[2]', stock_Image4='imgdata/stock/$pic[3]', stock_Ref='$ref', stock_Description='$desc1', stock_Maker='$maker', stock_Date='$date', stock_Weight='$weight', stock_Height='$height', stock_Depth='$depth',stock_Width='$width', stock_Price='$price', stock_Sold='$sold', stock_Active='$active', stock_DateTime='$dt2' where stock_Id=$sr") or die (mysql_error()); $flag=1; $conf="Data Updated Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_categories.php'>here</a> to continue"; $update="1"; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic1[]" id="pic1[]" size="50" /> </td> </tr> <input type="submit" name="btnsubmit" value="Submit"> <input type="submit" name="btndelete" value="Delete" DEFANGED_OnClick="return check();"> <input type="hidden" name="srno1" value="<?= $rows["stock_Id"];?>"> <input type="hidden" name="action" value="Upload"> All seems to be fine above, I can upload 1,2,3 or 4 images and the image goes into the server and the path to the database. But I then needed the option for my client to be able to click to edit a certain stock and then aswel as edit the other details, if he wanted to change one pic, no pics or all 4 he could and when he clicked submit, if there was a new image it would change if not it would stay as it is. So here is my attempt and at the moment it doesnt work, so I'm looking for help of any kid and anything can change. Code: [Select] $name=$_POST['txtname']; $ref=$_POST['Ref']; $desc=$_POST['e1m1']; $maker=$_POST['Maker']; $date=$_POST['Date']; $weight=$_POST['Weight']; $height=$_POST['Height']; $depth=$_POST['Depth']; $width=$_POST['Width']; $price=$_POST['txtprice']; $sold=$_POST['txtsold']; $meta=$_POST['txtmeta']; $active=$_POST['active']; $pcats=$_POST['pcats']; $subcats=$_POST['subcats']; $pic1=''; for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$pic1[$i]=$_FILES['pic1']['name'][$i]; else $pic1[$i]=''; } for($i=0;$i<4;$i++){ if(isset($_FILES['pic1']['name'][$i]))$path1= "./imgdata/stock/".$_FILES['pic1']['name'][$i]; //echo $_FILES['pic1']['tmp_name'][$i]." :". $path1; if(!empty($_FILES['pic1']['name'][$i])&&isset($_FILES['pic1']['name'][$i]))copy($_FILES['pic1']['tmp_name'][$i], $path1); } $q=mysql_query("insert into stock (stock_Name, stock_MetaTitle, parent_Category, sub_Category, stock_Ref, stock_Description, stock_Maker, stock_Date, stock_Weight, stock_Height, stock_Depth, stock_Width, stock_Price, stock_Sold, stock_Image, stock_Image2, stock_Image3, stock_Image4, stock_Active, stock_DateTime) values('$name','$meta','$pcats','$subcats','$ref','$desc','$maker','$date','$weight','$height','$depth','$width','$price','$sold','imgdata/stock/$pic1[0]','imgdata/stock/$pic1[1]','imgdata/stock/$pic1[2]','imgdata/stock/$pic1[3]','$active','$dt2')") or die (mysql_error()); $conf="Data Inserted Successfully - Click <a href='http://www.accendsandbox.co.uk/adminSallam/admin_stock.php'>here</a> to continue"; $update=1; Code: [Select] <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 1 (Main):</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p1" value="<?php echo $pic1;?>" /> <img src="<?php echo $pic1;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 2:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p2" value="<?php echo $pic2;?>" /> <img src="<?php echo $pic2;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 3:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p3" value="<?php echo $pic3;?>" /> <img src="<?php echo $pic3;?>" height="100px" /> </td> </tr> <tr> <td bgcolor="#A0B050" width="161"> <div style="font-family:Verdana, Arial, Helvetica, sans-serif; position:relative; font-size:12px; color:#293334; font-weight:bold; position:relative; float:left; left:1px;">Stock Image 4:</div> </td> <td bgcolor="#888888"> <input type="file" name="pic[]" size="50" /> <input type="hidden" name="p4" value="<?php echo $pic4;?>" /> <img src="<?php echo $pic4;?>" height="100px" /> </td> </tr> What happens above as its all on the same page, is when a stock item is selected to be edited the form to update the images changes to the image upload options above, instead of the original ones for a new stock item at the top of this post. I can provide anything you need to help me with this, so please can somebody take a look and see if it can be got working, as its been a long problem for me this. Cheers I know it needs a for loop, but i don't know where in the code i should be putting it? Code: [Select] function check_input($value) { // Stripslashes if (get_magic_quotes_gpc()) { $value = stripslashes($value); } // Quote if not a number if (!is_numeric($value)) { $value = "'" . mysql_real_escape_string($value) . "'"; } return $value; } $_POST = array_map('check_input', $_POST); $sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images) VALUES ({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname' )"; } if (!mysql_query($sql,$con)) { die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>'); } echo "<p align=center><b>1 testimonial added</b></p>"; mysql_close($con); Thanks in Advance, Steve I want to let users select and upload a file. The select form and upload sritp work when they are on different pages, but I want them on the same page with the upload script executing only if the form has been submitted. Here the upload form <!--select the file --> <form enctype="multipart/form-data" action="manage_files.php" method="POST">Please choose a file to upload: <input name="uploaded" type="file" /><input type="submit" value="Upload" /></form> ... and here's the upload code... <!--upload the file --> <?php if (isset($_POST['submit'])) { $target = "safes/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition //if ($uploaded_size > 350000) //{ //echo "Your file is too large.<br>"; //$ok=0; //} //if (!($uploaded_type=="application/zip")) { //echo "You may only upload ZIP files.<br>"; //$ok=0; //} //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } } ?> What am I missing? Thanks for any help! Hello,
I have multiple str_replace with file_put_contents in my script and it only seems to run the last str_replace.
If I remove the last one it runs the first one fine.
Code:
$file_name = "txt.txt"; Hello, all: been trying to convert this little single-file upload to multiple by naming each file form-field as "userfile[]" as it's supposed to automatically treat them as an array.. but no luck! Can you guide me as to what am I doing wrong?? appreciate the help! Code: [Select] <?php if (!isset($_REQUEST["seenform"])) { ?> <form enctype="multipart/form-data" action="#" method="post"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> <input type="submit" value="Upload"> <input type="hidden" name="seenform"> </form> <?php } else { // upload begins $userfiles = array($_FILES['userfile']); foreach ($userfiles as $userfile) { // foreach begins $uploaded_dir = "uploads/"; $userfile = $_FILES['userfile']["name"]; $path = $uploaded_dir . $userfile; if (move_uploaded_file($_FILES['userfile']["tmp_name"], $path)) { print "$userfile file moved"; // do something with the file here } else { print "Move failed"; } } // foreach ends } // upload ends ?> 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 have done a coding for image multiple upload , the coding is working perfectly when i store image in the image folder but when trying to insert the image name in database its not working. important thing is while we store the value of images it should store in single column seperated with comma or special character. like this id image 1 car.jpg,bike.jpg,sun.jpg pls help to me, thanks in advance. Here is the code. img.php <?php $max_no_img=5; // Maximum number of images value to be set here echo "<form method=post action=addimgck.php enctype='multipart/form-data'>"; echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>"; for($i=1; $i<=$max_no_img; $i++){ echo "<tr><td>Images $i</td><td> <input type=file name='images[]' class='bginput'></td></tr>"; } echo "<tr><td colspan=2 align=center><input type=hidden name='userid' value='68'></td></tr>"; echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>"; echo "</form> </table>"; ?> addimgck.php <?php ini_set('display_errors', 1); ini_set('error_reporting', E_ALL); function findexts ($filename) { $filename = strtolower('$filename') ; $exts = preg_split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } $ext = findexts ($_FILES['images']['name']) ; $ran = rand (); $ran2 = $ran."."; while(list($key,$value) = each($_FILES['images']['name'])) { if(!empty($value)) { $filename = $ran.$value; $filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line $add = "images/$filename"; $insert_query = 'insert into image ( photo ) values ( "'.$filename.'" )'; //echo $_FILES['images']['type'][$key]; // echo "<br>"; copy($_FILES['images']['tmp_name'][$key], $add); chmod("$add",0777); mysql_query($insert_query); } } ?> I have one input upload and need it to go to two directories here is my upload code that handles the move_upload_file portion. Code: [Select] move_uploaded_file($_FILES['fillPDF']['tmp_name'], $strNewsPath . $strFilename); Thanks in advance. <form id="test" action="<?php $_POST['SERVER_SELF'] ?>" method="POST" enctype="multipart/form-data" > <div class="wrap"> <p>upload image here for Contact Page</p> <input type="file" name="image"> <br> <input name="about1" type="submit" value="Upload image"> <br> </div> </form> <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100000"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['about'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=contactbg.'.'.jpg; //the new name will be containing the full path where will be stored (images folder) $newname="C:/xampp/htdocs/Dirk-taat/wp-content/themes/dirktaat/images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['about']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['about1'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=aboutme_bg.'.'.png; //the new name will be containing the full path where will be stored (images folder) $newname="C:/../.../../.../../.../images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['about1']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } } ?> the above code works only for 1 upload box if more than one upload box it does not upload the file. Thanks 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 I am trying to write a script to handle multiple image uploads however i cant get it to work i am a total novice in php so please be kind in your replys :-) [php] <?php $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.JPG','.PNG','.BMP','.GIF'); //These will be the types of file that will pass the validation. $upload_path = '../pic_upload/'; // The place the files will be uploaded to. foreach ($_FILES["pictures"]["error"] as $key => $error) { $filename = $_FILES['pictures']['name'][$key]; $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); if(!empty($filename)) //is it empty { if ($_FILES["pictures"]["size"][$key] >= 9000000) die ('Sorry the picture is too Big!'); } if(!empty($filename)) //Is it empty { if(!in_array($ext,$allowed_filetypes)) //Is the file Allowed die('The file you attempted to upload is not allowed! Pictures only!.'); } if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = $_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name, "$upload_path/$ran$name"); if (!$i++) print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>Untitled Document</title> </head> <body> <div align=\"center\"><img src=\".../image/8-1.gif\" width=\"100\" height=\"100\" /></div> <form id=\"form1\" name=\"form1\" method=\"get\" action=\"reg.php\"> <div align=\"center\"> <input type=\"submit\" name=\"button\" id=\"button\" value=\"Submit\" /> <input type=\"hidden\" name=\"reg\" value=\"6\"> <p>\n"; print "<input type=\"hidden\" name=\"pic$key\" value=\"$ran$name\">\n"; if (!$i++) print "</p> <p> <label> </div> </label> </p> </form> <p> </p> </body> </html>\n"; } } ?> [php] Hey guys, I am a newb but trying to figure out how I can upload multiple associated photo files. My code is working for one photo, however I would like to have multiple photos that are associated uploaded at the same time. I would like the photos save in a format such as: photo_filename1 = 100, photo_filename2 = 100_a I am using the following code with no luck, not sure how I can work this. Any help is much appreciated!!! Thanks in advance. <code> <?php include("config.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 preupload.php $photos_uploaded1 = $_FILES['photo_filename1']; $photos_uploaded2 = $_FILES['photo_filename2']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded1) ) { if($photos_uploaded1['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded1['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename1`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded1['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename1='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded1['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++; } //file2 while( $counter <= count($photos_uploaded2) ) { if($photos_uploaded2['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded2['type'][$counter], $known_photo_types)) { $result_final2 .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename2`) VALUES('0')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded2['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id."_1.".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename2='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded2['tmp_name'][$counter], $images_dir."/".$filename); $result_final2 .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final $result_final2 </body> </html> __HTML_END; ?> </code> Hey guys. I'm using this script to handle file (picture) uploads at the moment, and it works fine. Problem is though, I need to changeit to a multiple upload form (with 10 uploads per submit) and I dont know how to do it. I think ... I need to change this "<input type="file" name="image" >" to an array ... and put a "for each" loop or something somewhere ... but I really don't know what I am doing. Can someone please help? Thanks Gem <?php include ("includes/dbconnect120-gem.php"); //define a maxim size for the uploaded images define ("MAX_SIZE","500"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","150"); define ("HEIGHT","100"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded. $errors=0; if(isset($_POST['submit1']) && !$errors) { $sqlalbum="INSERT INTO album (album_name) VALUES ('$_POST[newalbumname]')"; mysql_query($sqlalbum) or die ('Error, album_query failed : ' . mysql_error()); } // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message //and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="uploads/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='uploads/thumbs/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters //the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { $album = $_POST['album']; $query = "INSERT INTO upload (name, path, album_id, thumbpath ) ". "VALUES ('$image_name', '$newname' , '$album', '$thumb_name')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form name="newalbum" method="post" action=""> <input name="newalbumname" type="text" size="30" maxlength="30" value="<?php echo $newalbumname; ?>" /> <input type="submit" name="submit1" value="Create Album" /> </form> <br /> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><select name="album"> <option value="select" selected="selected" >-Albums-</option> <?php $asql="select * from album order by album_id DESC"; $aresult=mysql_query($asql) or die(mysql_error());; while($arow=mysql_fetch_array($aresult)) { $album_id=$arow['album_id']; $album_name=$arow['album_name']; ?> <option value="<?php echo $album_id; ?>"><?php echo $album_name; ?></option> <?php } ?> </select> <tr><td><input type="file" name="image" ></td></tr> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr> </table> </form> </body> </html> |