PHP - Problems Adding Multiple Upload Fields To Upload Script
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 Similar TutorialsI 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 Hi guys, I've got an image uploader based on Uploadify, first let me set out what I want the script to do and what it currently does/doesn't do: Upload files of various types into folders named with the Order ID - OK Process the files by checking the file type and acting accordingly - OK Create thumbnails of the images in the /thumbs subdirectory - OK If the file is a PDF, create JPEG images of all pages and subsequent thumbnails - OK If the file is a ZIP, unzip and re-process the contents based on the above rules - FAIL As you can see I'm nearly at the end of my wishlist with this script, currently when it receives a ZIP file is unzip's it correctly placing the contents in the parent (Order-ID) directory however I'm then left with the same situation I have at the very beginning of the script, for example: File in -> "What kind of file are you?" -> Process file based on the answer. What I need to do is: File in -> "What kind of file are you? Oh! a Zip File, let's unzip and ask the same question of the contents!" -> Process contents. So basically I need to ask the same question twice, once of the zip and once of the contents of the unzipped file. This is where I'm struggling, someone told me to use a function which I tried but it kept breaking and I wasn't sure why. Therefore I have attached 2 files. 1 which currently works 99% except for "asking the question again" and one which doesn't work but I was told is the right way to do it File 1: Works 99%. Code: [Select] <?php /* TomBigFile v2.0 Based on Uploadify v2.1.4 Automatic folder creation dependant on order number with a thumbnail subdirectory. All files in are subject to a process which determines their type and acts accordingly. PDF's are automatically converted on the fly to 2 sets of JPEG's and stored accordingly to be accessed by Customer Accounts and Sales Order details area. Revised May 2011 */ // RECEIVE THE DATA FROM THE UPLOAD AND ASSIGN THE VARIABLES if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; // $fileTypes = str_replace('*.','',$_REQUEST['fileext']); // $fileTypes = str_replace(';','|',$fileTypes); // $typesArray = split('\|',$fileTypes); // $fileParts = pathinfo($_FILES['Filedata']['name']); // if (in_array($fileParts['extension'],$typesArray)) { // CREATE THE PARENT DIRECTORY BASED ON ORDER ID AND THE THUMBS SUBDIRECTORY mkdir(str_replace('//','/',$targetPath), 0755, true); mkdir($targetPath . "thumbs", 0755, true); // create thumbs dir move_uploaded_file($tempFile,$targetFile); echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile); // } else { // echo 'Invalid file type.'; // } } // BEGIN CHECKING THE IMAGE LOOKING AT THE FILE TYPE AND ACTING ACCORDINGLY $imgsize = getimagesize($targetFile); switch(strtolower(substr($targetFile, -3))){ case "pdf": $large = substr_replace($targetFile , 'jpg', strrpos($targetFile , '.') +1); $thumbnail = dirname($large).'/thumbs/'.basename(substr($large, 0, -4)."_thumb".strtolower(substr($large, -4))); $cmd = "$targetFile -write $large -thumbnail 64x64 $thumbnail "; exec("convert $cmd "); exit; break; case "jpg": $image = imagecreatefromjpeg($targetFile); break; case "png": $image = imagecreatefrompng($targetFile); break; case "gif": $image = imagecreatefromgif($targetFile); break; case "zip": $zip = new ZipArchive(); $zip->open($targetFile); $zip->extractTo($targetPath); $zip->close(); break; default: exit; break; } $width = 60; //New width of image $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions $src_w = $imgsize[0]; $src_h = $imgsize[1]; $picture = imagecreatetruecolor($width, $height); imagealphablending($picture, false); imagesavealpha($picture, true); $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); // SAVE THE IMAGE(S) if($bool){ switch(strtolower(substr($targetFile, -3))){ case "jpg": //header("Content-Type: image/jpeg"); $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "png": //header("Content-Type: image/png"); imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "gif": //header("Content-Type: image/gif"); imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; } } imagedestroy($picture); imagedestroy($image); echo '1'; // Important so upload will work on OSX ?> File 2: Doesn't work for me but I was told is correct method(s). Code: [Select] <?php /* TomBigFile v2.0 Based on Uploadify v2.1.4 Automatic folder creation dependant on order number with a thumbnail subdirectory. All files in are subject to a process which determines their type and acts accordingly. PDF's are automatically converted on the fly to 2 sets of JPEG's and stored accordingly to be accessed by Customer Accounts and Sales Order details area. Revised May 2011 */ if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; // $fileTypes = str_replace('*.','',$_REQUEST['fileext']); // $fileTypes = str_replace(';','|',$fileTypes); // $typesArray = split('\|',$fileTypes); // $fileParts = pathinfo($_FILES['Filedata']['name']); // if (in_array($fileParts['extension'],$typesArray)) { // Uncomment the following line if you want to make the directory if it doesn't exist mkdir(str_replace('//','/',$targetPath), 0755, true); mkdir($targetPath . "thumbs", 0755, true); // create thumbs dir move_uploaded_file($tempFile,$targetFile); echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile); // } else { // echo 'Invalid file type.'; // } } // start again here after ZIP!!!! function fileScanner($targetFile, $targetPath) { $imgsize = getimagesize($targetFile); $width = 60; //New width of image $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions $src_w = $imgsize[0]; $src_h = $imgsize[1]; $picture = imagecreatetruecolor($width, $height); imagealphablending($picture, false); imagesavealpha($picture, true); $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); if($bool){ switch(strtolower(substr($targetFile, -3))){ case "jpg": //header("Content-Type: image/jpeg"); $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "png": //header("Content-Type: image/png"); imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; case "gif": //header("Content-Type: image/gif"); imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); break; } } imagedestroy($picture); imagedestroy($image); } $imgsize = getimagesize($targetFile); switch(strtolower(substr($targetFile, -3))){ case "pdf": $large = substr_replace($targetFile , 'jpg', strrpos($targetFile , '.') +1); $thumbnail = dirname($large).'/thumbs/'.basename(substr($large, 0, -4)."_thumb".strtolower(substr($large, -4))); $cmd = "$targetFile -write $large -thumbnail 64x64 $thumbnail "; exec("convert $cmd "); exit; break; case "jpg": $image = imagecreatefromjpeg($targetFile); break; case "png": $image = imagecreatefrompng($targetFile); break; case "gif": $image = imagecreatefromgif($targetFile); break; case "zip": $zip = new ZipArchive(); $zip->open($targetFile); $zip->extractTo($targetPath); $zip->close(); fileScanner($targetFile, $targetPath); break; default: exit; break; } fileScanner($targetFile, $targetPath); // $width = 60; //New width of image // $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions // // $src_w = $imgsize[0]; // $src_h = $imgsize[1]; // // // $picture = imagecreatetruecolor($width, $height); // imagealphablending($picture, false); // imagesavealpha($picture, true); // $bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); // // if($bool){ // switch(strtolower(substr($targetFile, -3))){ // case "jpg": // //header("Content-Type: image/jpeg"); // $bool2 = imagejpeg($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // case "png": // //header("Content-Type: image/png"); // imagepng($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // case "gif": // //header("Content-Type: image/gif"); // imagegif($picture,$targetPath."thumbs/".substr($_FILES['Filedata']['name'], 0, -4)."_thumb".strtolower(substr($targetFile, -4))); // break; // } // } // // imagedestroy($picture); // imagedestroy($image); echo '1'; // Important so upload will work on OSX ?> If anyone could help me with this I'd greatly appreciate it, I've been reading so many guides on functions and arguments my brain is fried and I fear I've strayed from the subject of what I want to do! Many thanks. 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'; ?> 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 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 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 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 an upload form (which can be seen he http://kmkwebdevelopment.com/formtest/upload.php). There are currently 5 "upload" fields, and I would like to have it so that if a person requires more "upload" fields, they can click on a + sign or something and it will make 15 more "upload" fields drop down (so they can upload a total of 20 files at a time). Does anyone know a good way to do this? Thanks. <?php error_reporting(0); foreach($_POST as $key => $value){ if (is_array($value)) { $_values[$key] = join("%,% ",$value); }else $_values[$key] = $value; $_values[$key]=stripslashes($_values[$key]); } if (!isset($_POST["_referer"])) { @$_referer = $_SERVER["HTTP_REFERER"]; }else $_referer = $_POST["_referer"]; $_ErrorList = array(); function mark_if_error($_field_name, $_old_style = ""){ global $_ErrorList; $flag=false; foreach($_ErrorList as $_error_item_name){ if ($_error_item_name==$_field_name) { $flag=true; } } echo $flag ? "style=\"background-color: #FFCCBA; border: solid 1px #D63301;\"" : $_old_style; } function IsThereErrors($form, $_isdisplay) { global $_POST, $_FILES, $_values, $_ErrorList; $flag = false; if ($form > -1) { if ($_isdisplay) { echo "<div style=\"border: 1px solid; margin: 10px auto; padding:15px 10px 15px 50px; background-repeat: no-repeat; background-position: 10px center; color: #D63301; background-color: #FFCCBA; max-width:600px; background-image:url('".$_SERVER["PHP_SELF"]."?image=warning');\">"; } $flag = false; $req[0][] = array("firstname", "firstname is required."); $req[0][] = array("lastname", "lastname is required."); $req[0][] = array("email", "email is required."); $req[0][] = array("companynumber", "companynumber is required."); foreach($req[$form] as $field){ if (!isset($_values[$field[0]]) or ($_values[$field[0]]=="")) { $flag = true; if ($_isdisplay) { echo $field[1]."<br>"; $_ErrorList[] = $field[0]; } } } $files_req[0][] = array("upload1", "upload1 is required."); foreach($files_req[$form] as $field){ if (@$_FILES[$field[0]]["name"]=="") { $flag = true; if ($_isdisplay) { echo $field[1]."<br>"; $_ErrorList[] = $field[0]; } } } $fields[0][] = array("email", '/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}$/', true, "email should be valid e-mail address."); $fields[0][] = array("companynumber", '/^[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b$/', true, "companynumber should contain integer or floating point value only."); foreach($fields[$form] as $field){ if (!(preg_match($field[1],$_values[$field[0]])==$field[2]) && $_values[$field[0]]!=""){ $flag = true; if ($_isdisplay) { echo $field[3]."<br>"; $_ErrorList[] = $field[0]; } } } $files[0][] = array("upload1", "true", "true", "You are trying to upload file with not allowed extension.", "true", ""); $files[0][] = array("upload2", "true", "true", "", "true", ""); $files[0][] = array("upload3", "true", "true", "", "true", ""); $files[0][] = array("upload4", "true", "true", "", "true", ""); $files[0][] = array("upload5", "true", "true", "", "true", ""); foreach($files[$form] as $file){ $str = $file[1]; if (eval("if($str){return true;}")) { $_values[$file[0]] = $_FILES[$file[0]]["name"]; $dirs = explode("/","attachments//"); $cur_dir ="."; foreach($dirs as $dir){ $cur_dir = $cur_dir."/".$dir; if (!@opendir($cur_dir)) { mkdir($cur_dir, 0777);}} $_values[$file[0]."_real-name"] = "attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; copy($_FILES[$file[0]]["tmp_name"],$_values[$file[0]."_real-name"]); @unlink($_FILES[$file[0]]["tmp_name"]); }else{ $flag=true; if ($_isdisplay) { //$ExtFltr = $file[2]; //$FileSize = $file[4]; if (!eval("if($file[2]){return true;}")){echo $file[3];} if (!eval("if($file[4]){return true;}")){echo $file[5];} $_ErrorList[] = $file[0]; } } } if ($_isdisplay) { echo "</div>"; } } return $flag; } function display_page_upload_form($_iserrors) { global $_values, $_referer;?> <html><SCRIPT LANGUAGE = "JavaScript"> var fields = { "companynumber" : ["companynumber", /^[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b$/, true, "Your Company Number should be entered with no spaces or hyphens."], "email" : ["email", /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}$/, true, "Please ensure your email address is in a valid format."] }; var req = { "upload1" : ["upload1", "upload1 is required."], "companynumber" : ["companynumber", "company number is required."], "email" : ["email", "email is required."], "lastname" : ["lastname", "last name is required."], "firstname" : ["firstname", "first name is required."] }; var validate_form = true;function CheckForm(){HideAllErrors();if(!validate_form)return true;var LastErrorField=null;for(var i in fields){isError=ValidateField(fields[i][0],fields[i][1],fields[i][2],fields[i][3]);if(isError)LastErrorField=isError}for(var i in req){isError=isFilled(req[i][0],req[i][1]);if(isError)LastErrorField=isError}if(LastErrorField){LastErrorField.focus();return false}else return true}function ShowTooltip(type,field,message){var IE='\v'=='v';var container;if(!(container=document.getElementById('error_list'))){var container=(IE)?(document.createElement('<div name="error_list">')):(document.createElement('div'));container=document.createElement('div');container.setAttribute('id','error_list');document.body.appendChild(container)}if(!document.getElementById(field+'_tooltip')){var elem=(IE)?(document.createElement('<div name="myName">')):(document.createElement('div'));var elem2=(IE)?(document.createElement('<div name="myName2">')):(document.createElement('div'));div_id=field+'_tooltip';elem=document.createElement('div');elem.setAttribute('id',div_id);elem.className="fe-"+type+"-container";elem.onmouseover=function(){MoveDivToTop(this)};elem.onclick=function(){HideTooltip(this.id)};elem2=document.createElement('div');elem2.className="fe-"+type;elem2.innerHTML=message;parentField=document.getElementsByName(field);var f=0;while(parentField[f].type=='hidden')f++;with(elem.style){top=findPos(parentField[f])[0]+'px';left=findPos(parentField[f])[1]+parentField[f].offsetWidth+'px'}elem.appendChild(elem2);container.appendChild(elem)}}function ValidateField(name,rule,condition,message){fld=document.getElementsByName(name);var i=0;while(fld[i].type=='hidden')i++;if(!(((fld[i].value.match(rule)!=null)==condition)||(fld[i].value==""))){ShowTooltip('error',fld[i].name,message);return fld[i]}return null}function isFilled(name,message){fld=document.getElementsByName(name);var isFilled=false;var i=0;while(fld[i].type=='hidden')i++;var obj=fld[i];for(j=i;j<fld.length;j++){if((fld[j].type=='checkbox')||(fld[j].type=='radio')){if(fld[j].checked)isFilled=true}else{if(fld[j].value!="")isFilled=true}}if(isFilled){return null}else{ShowTooltip('error',name,message);return obj}}function FieldBlur(elemId){HideTooltip(elemId);fieldName=elemId.replace(/(\S{0,})_tooltip/,"$1");if(typeof fields[fieldName]!='undefined'){ValidateField(fields[fieldName][0],fields[fieldName][1],fields[fieldName][2],fields[fieldName][3])}if(typeof req[fieldName]!='undefined'){isFilled(req[fieldName][0],req[fieldName][1])}}function HideTooltip(elemId){var elem=document.getElementById(elemId);var parent=document.getElementById('error_list');if((elem)&&(parent))parent.removeChild(elem)}function HideAllErrors(){error_container=document.getElementById('error_list');if(error_container!=null){while(error_container.childNodes.length>0){error_container.removeChild(error_container.firstChild)}}}function MoveDivToTop(div_to_top){div_container=document.getElementById('error_list');for(i=0;i<div_container.childNodes.length;i++)div_container.childNodes[i].style.zIndex="998";div_to_top.style.zIndex="999"}function findPos(obj){var curleft=curtop=0;do{curleft+=obj.offsetLeft;curtop+=obj.offsetTop}while(obj=obj.offsetParent);return[curtop,curleft]} </SCRIPT> <style type="text/css"> .form_expert_style {display: none;}.fe-info,.fe-error{font:13px arial,helvetica,verdana,sans-serif;padding:2px;position:relative;top:-7px}.fe-error{border:solid 1px #d51007;background:#fbe3e4;color:#d51007}.fe-info{border:solid 1px #0187c5;background:#eff9ff;color:#0187c5}.fe-info-container,.fe-error-container{position:absolute;padding:0;border-left:8px solid transparent;-border-left:8px solid white;filter:progid:DXImageTransform.Microsoft.Chroma(color="white")}.fe-error-container{border-top:8px solid #d00}.fe-info-container{border-top:8px solid #0187c5} </style> <form class="uploadform" action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post" enctype="multipart/form-data" onSubmit="return CheckForm(this);"> <?php IsThereErrors("0", $_iserrors); ?> <input type="hidden" name="_referer" value="<?php echo $_referer ?>"> <input type="hidden" name="_next_page" value="1"> <p class="form_expert_style"><input name="URL" type="text" value=""/></p> <table> <tr> <td>First Name *</td> <td><input type='text' size='30' name='firstname' onBlur="FieldBlur(this.name+'_tooltip')" <?php mark_if_error("firstname", "") ?> value="<?php echo isset($_values["firstname"]) ? htmlspecialchars($_values["firstname"]) : "" ?>"></td> </tr> <tr> <td>Last Name *</td> <td><input type='text' size='30' name='lastname' onBlur="FieldBlur(this.name+'_tooltip')" <?php mark_if_error("lastname", "") ?> value="<?php echo isset($_values["lastname"]) ? htmlspecialchars($_values["lastname"]) : "" ?>"></td> </tr> <tr> <td>E-mail *</td> <td><input type='text' size='30' name='email' onblur="FieldBlur(this.name+'_tooltip')" <?php mark_if_error("email", "") ?> value="<?php echo isset($_values["email"]) ? htmlspecialchars($_values["email"]) : "" ?>"></td> </tr> <tr> <td>Company Number *</td> <td><input type='text' size='30' name='companynumber' onBlur="FieldBlur(this.name+'_tooltip')" <?php mark_if_error("companynumber", "") ?> value="<?php echo isset($_values["companynumber"]) ? htmlspecialchars($_values["companynumber"]) : "" ?>"></td> </tr> <tr> <td>Upload *</td> <td><input class="image" type='file' size='30' name='upload1' onBlur="FieldBlur(this.name+'_tooltip')" <?php mark_if_error("upload1", "") ?>></td> </tr> <tr> <td>Upload</td> <td><input class="image" type='file' size='30' name='upload2'></td> </tr> <tr> <td>Upload</td> <td><input class="image" type='file' size='30' name='upload3'></td> </tr> <tr> <td>Upload</td> <td><input class="image" type='file' size='30' name='upload4'></td> </tr> <tr> <td>Upload</td> <td><input class="image" type='file' size='30' name='upload5'></td> </tr> <tr> <td> </td> <td><input type="submit" name="SubmitBtn" onClick="CheckForm1();" value="SUBMIT" /></td> </tr> </table> </form> </html> <?php } function display_thankyou() { global $_values, $_referer;?> <html> <p style="margin-top:100px; padding-bottom:300px;"><b>Thank you for your submission</b></p> </html> <?php } function display_default() { ?> <!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><title>Successful submission</title><link rel="shortcut icon" href="http://forms-expert.com/images/favicon.ico" /><style>html,body,form,fieldset{margin:0;padding:0}html,body{ height:100%}body{color:#000;background:#FFF;font-family:Tahoma,Arial,Helvetica,sans-serif;line-height:160%}body#bd{padding:0;color:#333;background-color:#FFF}body.fs4{font-size:12px}.componentheading{color:#4F4F4F;font-family:"Segoe UI","Trebuchet MS",Arial,Helvetica,sans-serif;font-weight:bold}small,.small{color:#666;font-size:92%}ul{list-style:none}ul li{padding-left:30px;background:url(../images/bullet-list.gif) no-repeat 18px 9px;line-height:180%}.componentheading{padding:0 0 15px 0;margin-bottom:0px;color:#4F4F4F;background:url(http://forms-expert.com/images/dot.gif) repeat-x bottom;font-size:250%;font-weight:bold}#ja-header{height:60px;position:relative;z-index:999;width:920px;margin:0 auto;clear:both}#ja-containerwrap,#ja-footer{width:920px;margin:0 auto;clear:both}#main-container{ min-height:100%; /*height:100%;*/ position:relative}#ja-footerwrap{clear:both;border-top:1px solid #CCC;margin-top:10px;background:url(../images/grad2.gif) repeat-x top; position:absolute; bottom:0; width:100%; height:60px}#ja-footer{padding:15px 0;position:relative}#ja-footer small{padding:4px 0 0 10px;float:left;display:block;color:#999;font-style:normal;line-height:normal}small.ja-copyright{position:absolute;right:10px}#ja-footer a{color:#666;text-decoration:none}#ja-footer a:hover,#ja-footer a:active,#ja-footer a:focus{color:#666;text-decoration:underline}#ja-footer ul{margin:4px 0 5px 10px;padding:0;float:left;background:url(http://forms-expert.com/images/vline.gif) no-repeat center right;line-height:normal}#ja-footer li{margin:0;padding:0;display:inline;background:none}#ja-footer li a{padding:0 10px;display:inline;background:url(http://forms-expert.com/images/vline.gif) no-repeat center left;font-size:92%;line-height:normal}.clearfix:after{clear:both;display:block;content:".";height:0;visibility:hidden}* html >body .clearfix{width:100%;display:block}* html .clearfix{height:1%}/* Firefox Scrollbar Hack - Do not remove *//*html{margin-bottom:1px;height:100%!important;height:auto}*/a{color:#F90}a:hover,a:active,a:focus{color:#F90}#ja-containerwrap{padding:0;padding-bottom:60px}</style></head><body id="bd" class="fs4"><div id="main-container"><br><br><br><br><br><div id="ja-containerwrap"> <div id="ja-container" class="clearfix"><div style="padding: 20px 30px 20px 30px;"><div class="ja-innerpad clearfix"><div class="componentheading">Your submission was successful. Thank you.</div><p align="right">This form was processed by <a href="http://forms-expert.com">Forms Expert</a>.<p align="right">© 2009 Forms-Expert. </div></div></div></div><div id="ja-footerwrap"><div id="ja-footer" class="clearfix"><ul><li><a href="http://forms-expert.com">Visit Forms Expert</a></li><li><a href="http://forms-expert.com/form-processing-features/">Features</a></li><li><a href="http://forms-expert.com/download/">Download Beta</a></li><li><a href="http://forms-expert.com/support/">Support</a></li><li><a href="http://forms-expert.com/contactus/">Contact page</a></li></ul><small class="ja-copyright">© 2009 <a href="http://forms-expert.com/">Forms-Expert</a></small></div></div></div></body></html> <?php } function display_spam_warning() { ?> <html> <form action="" method="post"><style> .form_expert_style {display: none;} </style> <?php IsThereErrors("1", $_iserrors); ?> <input type="hidden" name="firstname" value="<?php echo htmlspecialchars($_values['firstname'])?>"> <input type="hidden" name="lastname" value="<?php echo htmlspecialchars($_values['lastname'])?>"> <input type="hidden" name="email" value="<?php echo htmlspecialchars($_values['email'])?>"> <input type="hidden" name="companynumber" value="<?php echo htmlspecialchars($_values['companynumber'])?>"> <input type="hidden" name="upload1" value="<?php echo htmlspecialchars($_values['upload1'])?>"> <input type="hidden" name="upload1_real-name" value="<?php echo htmlspecialchars($_values['upload1_real-name'])?>"> <input type="hidden" name="upload2" value="<?php echo htmlspecialchars($_values['upload2'])?>"> <input type="hidden" name="upload2_real-name" value="<?php echo htmlspecialchars($_values['upload2_real-name'])?>"> <input type="hidden" name="upload3" value="<?php echo htmlspecialchars($_values['upload3'])?>"> <input type="hidden" name="upload3_real-name" value="<?php echo htmlspecialchars($_values['upload3_real-name'])?>"> <input type="hidden" name="upload4" value="<?php echo htmlspecialchars($_values['upload4'])?>"> <input type="hidden" name="upload4_real-name" value="<?php echo htmlspecialchars($_values['upload4_real-name'])?>"> <input type="hidden" name="upload5" value="<?php echo htmlspecialchars($_values['upload5'])?>"> <input type="hidden" name="upload5_real-name" value="<?php echo htmlspecialchars($_values['upload5_real-name'])?>"> <input type="hidden" name="_referer" value="<?php echo $_referer ?>"> <input type="hidden" name="_next_page" value="2"> <p class="form_expert_style"><input name="URL" type="text" value=""/></p> <p align="center"><b>Your submission seems to be a SPAM. Please contact web site administrator or click "Back" button to return to the form.</b></p> <p align="center"><input type="submit" name="back" value="< Back"></p></form> </html> <?php } function BuildBody($body, $html, $num){ global $zag, $un; if ($html) { $zag[$num] = "--".$un."\r\nContent-Type:text/html;\r\n"; } else { $zag[$num] = "--".$un."\r\nContent-Type:text/plain;\r\n"; }; $zag[$num] .= "Content-Transfer-Encoding: 8bit\r\n\r\n$body\r\n\r\n"; } function SendEmails (){ global $_values, $zag, $un; $un = strtoupper(uniqid(time())); $to[0] .= htmlspecialchars($_values["companynumber"]) . "@aissolutions.ca"; $from[0] .= "".str_replace("%,%", ",", $_values['email']).""; $subject[0] .= "upload_form was submitted on ".date("F j, Y")." ".date("H:i").""; $head[0] .= "MIME-Version: 1.0\r\n"; $head[0] .= "From: ".str_replace("%,%", ",", $_values['email'])."\r\n"; $head[0] .= "X-Mailer: Forms Expert at www.forms-expert.com\r\n"; $head[0] .= "Reply-To: ".str_replace("%,%", ",", $_values['email'])."\r\n"; $head[0] .= "Content-Type:multipart/mixed;"; $head[0] .= "boundary=\"".$un."\"\r\n\r\n"; $EmailBody = "<html><body> Form was filled with the following data: <br><b>firstname:</b> ".htmlspecialchars($_values["firstname"])." <br><b>lastname:</b> ".htmlspecialchars($_values["lastname"])." <br><b>email:</b> ".htmlspecialchars($_values["email"])." <br><b>companynumber:</b> ".htmlspecialchars($_values["companynumber"])." <br><b>upload1:</b> ".htmlspecialchars($_values["upload1"])." <br><b>upload2:</b> ".htmlspecialchars($_values["upload2"])." <br><b>upload3:</b> ".htmlspecialchars($_values["upload3"])." <br><b>upload4:</b> ".htmlspecialchars($_values["upload4"])." <br><b>upload5:</b> ".htmlspecialchars($_values["upload5"])." </body></html> "; BuildBody($EmailBody, True, 0); for ($i=0;$i<=0;$i++){ mail($to[$i], $subject[$i], $zag[$i], $head[$i]); } } $actions = array ("display_page_upload_form","display_thankyou"); session_start(); if(!isset($_SESSION["FormSent"])) { $_SESSION["FormSent"] = time(); $delta = -1; } else { $delta = time() - $_SESSION["FormSent"]; } if (((strlen(trim(@$_POST["URL"])) > 0) or (($delta>-1)and($delta<2)))and(!isset($_POST["back"]))){ display_spam_warning(); }else{ unset($_SESSION["FormSent"]); if (in_array($_GET["image"], array("warning"))) { header("Content-type: image/png"); echo base64_decode("iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKOWlDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanZZ3VFTXFofPvXd6oc0w0hl6ky4wgPQuIB0EURhmBhjKAMMMTWyIqEBEEREBRZCggAGjoUisiGIhKKhgD0gQUGIwiqioZEbWSnx5ee/l5ffHvd/aZ+9z99l7n7UuACRPHy4vBZYCIJkn4Ad6ONNXhUfQsf0ABniAAaYAMFnpqb5B7sFAJC83F3q6yAn8i94MAUj8vmXo6U+ng/9P0qxUvgAAyF/E5mxOOkvE+SJOyhSkiu0zIqbGJIoZRomZL0pQxHJijlvkpZ99FtlRzOxkHlvE4pxT2clsMfeIeHuGkCNixEfEBRlcTqaIb4tYM0mYzBXxW3FsMoeZDgCKJLYLOKx4EZuImMQPDnQR8XIAcK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l/f/1j+HrvNoOquhrbk9vcqUBVRwECiIWZjV36x6PXDN/+fmX4D7QAhJnYIJYxMUEiiRFU2AEx039YjvnHwPRxPwMX435gOQG1ENpnAKljAOL/oMgF8YHmgNT8h2bPL08+MrAAKywuPhYzkBaAAGL59vnVqSf3GBgUBYFFOjcjAzMnE7CEA1oGrAaYWBnBIQDyNZhmRDgI0q2BOIqJAWIZsPQB0/+hoQELgb8//0NyE9Alv7//Y7h/7gnD67cMm0FGAAQQi0VQ2frbpzZOPn37Rryk6H8+7l8sDGzfmBmYQaHAxAi2HGQRjIZ3qRiRa0/UnhM4KmA0KE39/sfw6/t/hl8f/zA8fwrMrFKqS0z9/dtAygECiBFUBnx4cZvh8/tnGoyMzLJAO7mAQc8G8TuSlaT0YRlRa3dgsfwXaM0vYFQB8Z8XvIJSVwQl1UBlKgNAADHiaTwyYRhFHviPhDEAQACx4HA7I5UsZ8BiDopDAAIMAP+QrU5p/QTlAAAAAElFTkSuQmCC"); }else{ if (isset($_POST["_next_page"])) { $_next_page = $_POST["_next_page"]; }else $_next_page = 0; if (isset($_POST["back"])) { call_user_func($actions[$_next_page-2],false); }else if (IsThereErrors($_next_page-1, false)){ call_user_func($actions[$_next_page-1],true); }else { call_user_func($actions[$_next_page+0],false); if ($_next_page == count($actions)-1) { SendEmails(); session_destroy(); } } } } ?> Hey guys!
I'm trying to add an upload feature to my contact form. I had one before that simply added the image under the text in the email not as an actual attachment and it was pretty easy but I lost the code and can’t seem to find it again. But I seem to be having a problem finding a form that can help me add this. As of now the code in HTML has the upload but the PHP doesn’t at all.
If anyone could help me add the rest of the PHP code I'd really appreciate it!
HTML:
<form name="htmlform" method="post" action="oc.php"><label for="fname"><p>Full Name:</p></label> <input type="text" name="fname" maxlength="50" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td valign="top"> <label for="phone"> <p>Phone Number: </p></label> <input type="text" name="phone" maxlength="50" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td valign="top"> <label for="email"> <p> Email Address: </p></label> <input type="text" name="email" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> </tr> <tr> <td> <h4>DELIVERY INFORMATION:</h4> <label for="address"> <p>Address: </p></label> <input type="text" name="address" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="city"> <p>City: </p></label> <input type="text" name="city" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="state"> <p>State: </p></label> <input type="text" name="state" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="zip"> <p>Zip Code: </p></label> <input type="text" name="zip" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <h4>INFORMATION:</h4> <label for="first"> <p>First Name: </p></label> <input type="text" name="first" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="last"> <p>Last Name: </p></label> <input type="text" name="last" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="rec"> <p>Recommendation ID Number: </p></label> <input type="text" name="rec" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="exp"> <p>Recommendation Experation Date: </p></label> <input type="text" name="exp" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="doc"> <p>Doctors Name: </p></label> <input type="text" name="doc" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="docphone"> <p>Doctors Phone Number: </p></label> <input type="text" name="docphone" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> <label for="ver"> <p>Verification Website: </p></label> <input type="text" name="ver" maxlength="80" size="60" style="color:#000;" required="required"> </td> </tr> <tr> <td> </td> </tr> <tr> <td valign="top"><label for="message"><p>How did you hear about us?</p></label><textarea name="message" id="message" style="background-color:#fff; color:#000;" cols="45"/></textarea></td> </tr> <tr> <td colspan="2" style="text-align:left"> <p> Upload Recommendation:</p> <input type="file" name="pic" id="pic"> <br /> <p> Upload California State ID:</p> <input type="file" name="id" id="id"> <br /> <br /> <input type="image" value="submit"img src="img/sub.png" onmouseover="this.src='img/sub1.png'" onmouseout="this.src='img/sub.png'" /> </form>PHP: <?php // first clean up the input values foreach($_POST as $key => $value) { if(ini_get('magic_quotes_gpc')) $_POST[$key] = stripslashes($_POST[$key]); $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key])); } $ip=$_SERVER['REMOTE_ADDR']; $email_to = "info@example.com"; $email_subject = "Register"; $email_message .= "Full Name: ".$_POST["fname"]."\n"; $email_message .= "Phone Number: ".$_POST["phone"]."\n"; $email_message .= "Email Address: ".$_POST["email"]."\n"; $email_message .= "Address: ".$_POST["address"]."\n"; $email_message .= "City: ".$_POST["city"]."\n"; $email_message .= "State: ".$_POST["state"]."\n"; $email_message .= "Zip Code: ".$_POST["zip"]."\n"; $email_message .= "First Name: ".$_POST["first"]."\n"; $email_message .= "Last Name: ".$_POST["last"]."\n"; $email_message .= "Recommendation ID Number: ".$_POST["rec"]."\n"; $email_message .= "Recommendation Exp Date: ".$_POST["exp"]."\n"; $email_message .= "Doctors Name: ".$_POST["doc"]."\n"; $email_message .= "Doctors Phone Number: ".$_POST["docphone"]."\n"; $email_message .= "Verification Website: ".$_POST["ver"]."\n"; $email_message .= "Message: ".$_POST["message"]."\n"; $userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL ); if( ! $userEmail ){ exit; } //email headers $headers = 'From: '.$_POST["email"]."\r\n". 'Reply-To: '.$_POST["email"]."\r\n" . 'X-Mailer: PHP/' . phpversion(); echo (mail($email_to, $email_subject, $email_message, $headers) ? "<html><head><meta http-equiv='Refresh' content='0; url=http://www..com/thankyou.html'><body bgcolor='#fff'> ":"<html><body bgcolor='#fff'><center><font color='white'><h2>We're sorry, something went wrong.</h2></font><p><font color='white'>Please return to <a href='http://www..com'></a>.</font></p></center></body></html>"); $ip=$_SERVER['REMOTE_ADDR']; $email_to = $_POST["email"]; $email_subject = "420 In Action"; $email_message1 = "Welcome! Sincerely, "; //email headers $headers = 'From: '.$_POST["email"]."\r\n". 'Reply-To: '.$_POST["email"]."\r\n" . 'X-Mailer: PHP/' . phpversion(); echo (mail($email_to, $email_subject, $email_message1, $headers) ? "":""); exit(); // test input values for errors $errors = array(); if(strlen($fname) < 2) { if(!$fname) { $errors[] = "You must enter a name."; } else { $errors[] = "Name must be at least 2 characters."; } } if(!$email) { $errors[] = "You must enter an email."; } else if (!validEmail($email)) { $errors[] = "You must enter a valid email."; } if($errors) { // output errors to browser and die with a failure message $errortext = ""; foreach($errors as $error) { $errortext .= "<li>".$error."</li>"; } die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>"); } // check to see if email is valid function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { $isValid = false; } // local part length exceeded else if ($domainLen < 1 || $domainLen > 255) { $isValid = false; } // domain part length exceeded else if ($local[0] == '.' || $local[$localLen-1] == '.') { $isValid = false; } // local part starts or ends with '.' else if (preg_match('/\\.\\./', $local)) { $isValid = false; } // local part has two consecutive dots else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { $isValid = false; } // character not valid in domain part else if (preg_match('/\\.\\./', $domain)) { $isValid = false; } // domain part has two consecutive dots else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { $isValid = false; } // domain not found in DNS } return $isValid; } ?> Hello, I am making an upload script and I want to restrict all file types except png, jpg, and gif. I can't seem to figure it out and help would be appreciated!! <?php $target = "images/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 230000) { echo "Your file is too large.<br>"; $ok=0; } if (!($uploaded_type=="image/gif")) { echo "You may only upload GIF 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."; } } ?> Hello: I wanted to learn how to add a file browse/save and send photo to a contact form. Form works fine, but I am trying to add this so a user can upload and send a photo of his or her artwork along with the contact information. Can someone tell me how this work? My other attempts failed so I'm trying to start with a clean form. This is the code I currently have: Code: [Select] <?php $error = NULL; $myDate = NULL; $FullName = NULL; $Address = NULL; $City = NULL; $State = NULL; $Zip = NULL; $Phone = NULL; $Email = NULL; $Website = NULL; $Comments = NULL; if(isset($_POST['submit'])) { $myDate = $_POST['myDate']; $FullName = $_POST['FullName']; $Address = $_POST['Address']; $City = $_POST['City']; $State = $_POST['State']; $Zip = $_POST['Zip']; $Phone = $_POST['Phone']; $Email = $_POST['Email']; $Website = $_POST['Website']; $Comments = $_POST['Comments']; if(empty($FullName)) { $error .= '<div style=\'margin-bottom: 6px;\'>- Enter your Name.</div>'; } if(empty($Email) || !preg_match('~^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$~',$Email)) { $error .= '<div style=\'margin-bottom: 6px;\'>- Enter a valid Email.</div>'; } if($error == NULL) { $sql = sprintf("INSERT INTO myContactData(myDate,FullName,Address,City,State,Zip,Phone,Email,Website,Comments) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')", mysql_real_escape_string($myDate), mysql_real_escape_string($FullName), mysql_real_escape_string($Address), mysql_real_escape_string($City), mysql_real_escape_string($State), mysql_real_escape_string($Zip), mysql_real_escape_string($Phone), mysql_real_escape_string($Email), mysql_real_escape_string($Website), mysql_real_escape_string($Comments)); if(mysql_query($sql)) { $error .= '<div style=\'margin-bottom: 6px;\'>Thank you for contacting us. We will reply to your inquiry shortly.<br /><br /></div>'; mail( "mt@gmail.com", "Contact Request", "Date Sent: $myDate\n Full Name: $FullName\n Address: $Address\n City: $City\n State: $State\n Zip: $Zip\n Phone: $Phone\n Email: $Email\n Website: $Website\n Comments: $Comments\n", "From: $Email" ); unset($FullName); unset($Address); unset($City); unset($State); unset($Zip); unset($Phone); unset($Email); unset($Website); unset($Comments); } else { $error .= 'There was an error in our Database, please Try again!'; } } } ?> <form name="myform" action="" method="post"> <input type="hidden" name="myDate" size="45" maxlength="50" value="<?php echo date("F j, Y"); ?>" /> <div id="tableFormDiv"> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">* - Required</span></span> <span class="floatFormLeft"> </span></fieldset> <?php echo '<span class="textError">' . $error . '</span>';?> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">*</span> Full Name:</span> <span class="floatFormLeft"><input type="text" name="FullName" size="45" maxlength="50" value="<?php echo $FullName; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Address:</span> <span class="floatFormLeft"><input type="text" name="Address" size="45" maxlength="50" value="<?php echo $Address; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">City:</span> <span class="floatFormLeft"><input type="text" name="City" size="45" maxlength="50" value="<?php echo $City; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">State:</span> <span class="floatFormLeft"><input type="text" name="State" size="45" maxlength="50" value="<?php echo $State; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Zip:</span> <span class="floatFormLeft"><input type="text" name="Zip" size="45" maxlength="50" value="<?php echo $Zip; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Phone:</span> <span class="floatFormLeft"><input type="text" name="Phone" size="45" maxlength="50" value="<?php echo $Phone; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">*</span> Email:</span> <span class="floatFormLeft"><input type="text" name="Email" size="45" maxlength="50" value="<?php echo $Email; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Website:</span> <span class="floatFormLeft"><input type="text" name="Website" size="45" maxlength="50" value="<?php echo $Website; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Comments:</span> <span class="floatFormLeft"><textarea name="Comments" cols="40" rows="10"><?php echo $Comments; ?></textarea></span></fieldset> </div> <input type="submit" name="submit" value="Submit" class="submitButton" /><br /> </form> Thanks very much! Hi, I have a basic form that lets people enter details Code: [Select] <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Second name: <input type="text" name="sname" /> <input type="submit" /> </form> And the standard insert in sql command. Im now looking to add a image uplad field the the same form. I have tried several methods off the internet but i cant get any to work. I would like the form to upload the image into the directory '../images' and then save the path to the file in the database, e.g. 'images/picture.jpg'. Can anyone point me in the right direction please. Im guessing i will have to use the file input type but i cant get any of it to work. Thanks Hiya all, Firstly thanks for the previous help with the arrays and that... you guys (or girls) ROCK ! But now I am stuck... lol. I am creating a simple motor dealer script for a friend with a garage and a few cars. The idea is... they fill in the form... upload the image(s) and then it adds it in to the database and displays the info on the page with other cars. So far I have got it to array all the info in the database how I want (thanks to you lot !). Now I need to add another box on the add vehicle page to upload photos and then on the show vehicles page I need it to show the uploaded photos next to the vehicles info. This is what I have so far: showvehicles.php: <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Current Showroom</B></CENTER> <BR> <!-- VIEWING BIT --> <?php include('dbconnect.php') ?> <?php // Make a MySQL Connection $query = "SELECT * FROM cars"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "<TABLE CELLPADDING=0 CELLSPACING=0 WIDTH=100% BORDER=0>"; echo "<TR />"; echo "<TD WIDTH=30% VALIGN=TOP />"; echo " <IMG SRC=immg.gif /> "; echo "<br />"; echo "</TD>"; echo "<TD WIDTH=10 VALIGN=TOP />"; echo " "; echo "</TD>"; echo "<TD />"; echo "<font size=3 face=arial /><B >"; echo $row['CarPrice']; echo "</B><font size=2 face=arial />"; echo "<br />"; echo $row['CarTitle']; echo "<br />"; echo "Vehicle Type: "; echo $row['CarName']; echo "<br />"; echo "Vehicle Mileage: "; echo $row['CarMiles']; echo "<br />"; echo "Description: "; echo "<br />"; echo "<br />"; echo $row['CarDescription']; echo "<br />"; echo "</TD>"; echo "</TR>"; echo "</TABLE>"; echo "<hr WIDTH=100% COLOR=BLACK />"; } ?> <!-- END OF VIEWING BIT --> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> AddVehicle.php <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Add a Vehicle</B></CENTER> <BR> <form action="inserts.php" method="post"> <CENTER>Vehicle Name:</CENTER> <CENTER><input type="text" name="CarName"></CENTER> <br> <CENTER>Vehicle Type:</CENTER> <CENTER><input type="text" name="CarTitle"></CENTER> <br> <CENTER>Vehicle Price:</CENTER> <CENTER><input type="text" name="CarPrice"></CENTER> <br> <CENTER>Vehicle Mileage:</CENTER> <CENTER><input type="text" name="CarMiles"></CENTER> <br> <CENTER>Vehicle Description:</CENTER> <CENTER><textarea name="CarDescription" rows="10" cols="30"></textarea></CENTER> <br> <CENTER><input type="Submit"></CENTER> </form> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> inserts.php (Actually handles adding info to the database thats been typed in form) <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Vehicle Added</B></CENTER> <BR> <?php mysql_connect("localhost", "wormste1_barry", "barry") or die(mysql_error()); mysql_select_db("wormste1_barry") or die(mysql_error()); $CarName = mysql_real_escape_string(trim($_POST['CarName'])); $CarTitle = mysql_real_escape_string(trim($_POST['CarTitle'])); $CarPrice = mysql_real_escape_string(trim($_POST['CarPrice'])); $CarMiles = mysql_real_escape_string(trim($_POST['CarMiles'])); $CarDescription = mysql_real_escape_string(trim($_POST['CarDescription'])); mysql_query("INSERT INTO cars (CarName, CarTitle, CarPrice, CarMiles, CarDescription) VALUES('$CarName', '$CarTitle', '$CarPrice', '$CarMiles', '$CarDescription' ) ") or die(mysql_error()); echo "The vehicle data has been added!"; ?> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> If anyone can help me... much appreciated. I googled it and it started quoting BLOBS and stuff... i was confused Hey there - how are you? I'm trying to add up multiple fields from a table and it's mostly working but I have one curious error. It always seems to miss the field upgrade6_fee. I'm totally baffled. I thought it was my syntax but I'm not seeing anything wrong with it. Any ideas? Otherwise it all seems to be working. <?php $query = "SELECT fee1, upgrade3_fee, upgrade4_fee, upgrade5_fee, upgrade6_fee, upgrade7_fee, SUM(fee1 + upgrade3_fee + upgrade4_fee + upgrade5_fee + upgrade6_fee + upgrade7_fee) AS ttotal FROM Register"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo number_format(($row['ttotal']), 2); } ?> I'm trying to add a file size limit to my upload form-code (below) I'm trying to upload images to my server using the $_FILES array but having issues. Here is the upload section from my form: Code: [Select] Cover Art:<input name="coverArt" type="file" /> and my upload script I'm working with: $targetFile="coverart/" . $_FILES['coverArt']['name']; if (file_exists($targetFile)) { echo $targetFile . "<br />"; } if (move_uploaded_file($_FILES['coverArt']['tmp_name'], $targetFile)) { echo "Cover art success"; } else { echo "COVER ART ERROR"; } I'm trying to upload these images to a folder on my server called coverart, however file_exists always seems to be true no matter what and echoing $targetFile only shows my folder name "coverart/" without the filename. So of course move_uploaded_file isn't working either. Any suggestions? Heya all, as the title says, i meet some issues when uploading files to my server, here is the code;
$anime = $_POST['anime']; $anime = $file = str_replace(' ', '\ ', $anime); $anime = "Sous-titres/".$anime."/"; $target_dir = $anime; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; if(isset($_POST["submit"])) { // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 50000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { var_dump ($target_dir); echo "Sorry, there was an error uploading your file."; } } }So, i'm attempting to acces to a directory taking the name of the anime that the admin put in the input type="text", for upload the file selected in. Error with the var_dump: string(28) "Sous-titres/Akame\ ga\ kill/" Sorry, there was an error uploading your file. Hope you can help me ! Edited by Zane, 08 December 2014 - 10:48 AM. 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] |