PHP - Can Somebody Help Me Make My Single File Upload Script Into A Multiple One?
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 Similar TutorialsHello, 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 ?> How do I Upload Multiple Files using a PHP form and script? 10 files at one time would be great. Ultimately I need a photo upload and management script. Here is my current single file upload form: <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Upload a Photo:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> Here is the Php Script: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 200000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "uploads/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> 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 Hey all, I am building a simple cms. I have a posts table and I have an images table. A post has many images and images has a foreign key to the posts table. So when a user edits, updates, creates, and deletes a post, they affect the images related to the post. Sometimes a post can have more than one image, like three images. Hence I rendered this in the view (note that I am using a datamapper that converts tables to objects and fields to key/value pairs): Code: [Select] foreach($records as $post){ echo form_open_multipart("homes/update/$post->id"); //File uploads require a multipart form. Default form handling uses the application/x-www-form-urlencoded content type. Multipart forms use the multipart/form-data encoding. //this is critical to pass the id as part of the action attribute of the form, so we can use our params hash to target the id to update the specific record echo label('Update Title'); echo form_input('title',$post->title); echo label('Update Body'); echo form_textarea('body',$post->body); $images = $post->images->include_join_fields()->get(); if(!is_null($images->image_file_name)){ echo label('Update Images'); foreach($images as $image){ echo form_upload('image_file_name',$image->image_file_name); } } } echo form_submit('submit','Update'); The above line of code will render a few input file types. The problem occurs during posting to my update method. It is looking for one parameter from the input file field and so if I upload three different images, it will only look for one and write only one to database: Code: [Select] $field_name = 'image_file_name'; if ( ! $this->upload->do_upload($field_name)){ $error = array('error' => $this->upload->display_errors()); echo $error['error']; // redirect('homes/edit'); } else { $data = array('upload_data' => $this->upload->data()); $image_file_name = $data['upload_data']['file_name']; Is it possible to do wht I am trying to do? Should I only have on input file type per form submission or is that I need to fix the code to accomodate for multiple submissions by creating an array of sorts? Thanks for response. Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." Okay so my news script is set to view only 10 pieces of news. But I want it so that it starts a new page once I have more than 10 pieces of news. Code: [Select] <?php require("functions.php"); include("dbconnect.php"); session_start(); head1(); body1(); new_temp(); sotw(); navbar(); $start = 0; $display = 10; $query = "SELECT * FROM news ORDER BY id DESC LIMIT $start, $display"; $result = mysql_query( $query ); if ($result) { while( $row = @mysql_fetch_array( $result, MYSQL_ASSOC ) ) { news_box( $row['news'], $row['title'], $row['user'], $row['date'], $row['id'] ); } mysql_free_result($result); } else { news_box( 'Could not retrieve news entries!', 'Error', 'Error', 'Error'); } footer(); mysql_close($link); ?> I tried a few things but they failed....miserably. 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'; ?> Hello i need help, I am creating a small social networking website in which i want dat a user can upload music files as well with some descriptions ,the description and file path should be stored in database and the mp3 file should be stored in a seprate folder i want a PHP script for this. If any one knows it then please help me. 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 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 can someone assist me with adding a second upload that grabs all files from within a directory. 1. user select .csv file (coding down for that) 2. user select folder with .docx files in side (this folder will only have docx files) 3. on submit .csv and all .docx files are upload to /temp_docx/ folder 4. the .csv has a matching docx_id that relates to the .docx file name (ex file 1.docx == docx_id = 1 in the csv file) so every time an insert is done a move_file happens and 1.docx would be moved to /docx_files/ 5. and if there is ever an error or no match at the end output all errors. I think the part where i'm stuck and confused the most is handling the second upload where all docx files in the folder are upload and looped through moving and inserting Code: [Select] <?php if(isset($_POST['submit'])) { $filename = file_get_contents($_FILES['uploadedfile']['tmp_name']); $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) { $import="INSERT into kmmb_member1(docx_id,no_ahli,no_pin,nama,no_ic_baru,no_ic_lama) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='import.php' method='post'>"; print "Type file name to import:<br />"; print "Select csv file: <input name='uploadedfile' type='file' /><br />"; print "<input type='submit' name='submit' value='submit' /></form>"; } ?> Hi Guys, I need help for in storing data from PHP from array in mysql. I'm very new to PHP/Mysql and have started learing it just few weeks back. I'm tryting to build a website for myself. I'm having tough time trying to insert the data from Form in mysql. I have a form where user update the company name and insert there product name with there image. I want to rename the image with the corresponding text field value and insert the upload path in the table. my FORM Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> body,td,th { color: #000; font-family: Tahoma, Geneva, sans-serif; font-size: 80%; } body { background-color: #9CF; } table { background: #CCF; } th { font: bold normal 16px/normal "Times New Roman", Times, serif; text-transform: capitalize; color: #00F; background: #FFC; } td { font: bold 14px Georgia, "Times New Roman", Times, serif; text-transform: capitalize; color: #3A00FF; background: #FF9; } </style> </head> <body> <form action="upload-file1.php" method="post" enctype="multipart/form-data" name="form"> <strong>Company Name:</strong> <input name="product" type="text" /> <br /> <table> <tr bgcolor="#FF9900"> <th colspan="3" bgcolor="#CCFFFF">filter </th> <th colspan="5" bgcolor="#CCFFFF">heater</th> </tr> <tr><td>filter1</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater1: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter2</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater2: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter3</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater3: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter4</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater4: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter5</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater5: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> </table> <br /> <br /> <input name="submit" type="submit" value="submit" /> </form> </body> </html> my PHP Code Code: [Select] <?php require("connect.php"); ?> <?php $product = $_POST['product']; echo $product; if(isset($_POST["submit"])){ $sql = "INSERT INTO company (product) VALUES ('$product')"; $query = mysql_query($sql) OR DIE(mysql_error()); $comp_id = mysql_insert_id(); echo $sql; } ?> <?php function filter() { if(isset($_POST['submit'])) { foreach($_POST['filter'] as $key => $val) { if(trim($val) != '') $filter[] = $val; } $total_records_filter = count($filter); for($i = 0; $i < $total_records_filter; $i++) { $prod_val = $filter[$i]; $sql_prod = "INSERT INTO filter(filter_id, filter) VALUES('', '$prod_val')"; echo $sql_prod.'<br>'; mysql_query($sql_prod) OR die(mysql_error()); } } } filter(); function heater() { if(isset($_POST['submit'])) { foreach($_POST['heater'] as $key => $val) { if(trim($val) != '') $heater[] = $val; } $total_records_heater = count($heater); for($i = 0; $i < $total_records_heater; $i++) { $dir_val = $heater[$i]; $sql_dir = "INSERT INTO heater(heater_id, heater) VALUES('', '$dir_val')"; echo $sql_dir.'<br>'; mysql_query($sql_dir) OR die(mysql_error()); } } } heater(); ?> <?php mysql_close($link)?> My Table structure company comp_id int(5) PK product varchar(50) No filter filter_id int(5) PK filter varchar(25) No filter_path varchar(100) No heater heater_id int(5) PK heater varchar(25) No heater_path varchar(100) No company_filter id int(5) PK comp_id int(5) PK FK (From company table) filter_id int(5) PK FK (From filter table) company_heater id int(5) PK comp_id int(5) PK FK (From company table) heater_id int(5) PK FK (From heater table) Regards BW This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=357764.0 I have looked around all overr, but cant find what im looking for. Everything I have found is about uploading multile files, what I need to do is upload one file and copy it so there is 3 files. Here is an example of what I need to accomplish. Upload file picture1.jpg From picture1.jpg create 3 files - smallimage_picture1.jpg, largeimage_picture1.jpg & smallimage_picture1_thumb.jpg Each file will need to be copied to a /products directory and also an entry for each file name placed in mysql database table. I don't think this is as simple as it sounds to do in PHP, but i am very willing to learn so if anyone knows of a good tutorial that get get me started that would be super. regards DB i need to upload files to a different folder dependint on option in form, make thumbnails, and store title and src for image and thumb in database table dependant on category. i think i'm pretty close, but there's still something wrong. Here is my upload form : Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Photo: <input type="file" name="photo"><br> Category: <select name="cat"> <option value="weddings">Weddings</option> <option value="music">Music</option> <option value="portraits">Portraits</option></select> Title: <input type="text" name="title"><br> <input type="submit" value="Upload photo"> </form> form processed by upload.php : Code: [Select] <?php require "db.php"; //Get form info $name=$_POST['name']; $title=$_POST['title']; $category=$_POST['cat']; $pic=($_FILES['photo']['name']); //set target dir source file width height $target = $cat."/"; $src = $target . basename( $_FILES['photo']['name']); $destination = $cat."/thumbs"; $thumbsrc = $destination . basename( $_FILES['photo']['name']); $width = 200; $height = 200; header("content-type: image/jpeg"); $src_img = imagecreatefromjpeg("$src"); $srcsize = getimagesize("$dest"); $dst_img = imagecreatetruecolor($width, $height); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $srcsize[0], $srcsize[1]); imagejpeg($dst_img); //Unstert into db mysql_query("INSERT INTO `$category` VALUES ('$name', 'Stitle', '$src, $thumbsrc')") ; //move photo if(move_uploaded_file($_FILES['photo']['tmp_name'], $fulltarget)) { //Ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //not ok echo "Sorry, there was a problem uploading your file."; } ?> call a script from main page Code: [Select] <div class="gallery"> <?php include "weddings/get.php" ?> </div> <div class="gallery"> <?php include "music/get.php" ?> </div> get.php displays links Code: [Select] <?php include "db.php"; $cat = weddings; $q = "SELECT id, title, src, thumbsrc FROM $cat"; $result = $mysqli->query($q) or die(mysqli_error($mysqli)); if ($result) { echo "<ul id='photos'> \n"; while ($row = $result->fetch_object()) { $title = $row->title; $src = $row->src; $thsrc = $row->thumbsrc; $id = $row->id; echo "<a href='$src' class="lightbox" rel="$cat" title="$name - $title"><img src='$thsrc' id='$id' alt='$name' /></a>": } echo "</ul>"; } ?> I think i'm going along the right sort of path, but i'm not sure. Hey all So have been working on a file upload script, it was uploading the file but also adding the path name instead of NULL to mysql when no image was to upload, that is now fixed however now it won't upload the actual image to the directory. I tried undoing the mysql changes but it still won't upload the image to the directory. Am testing on my own computer using xampp so no file permission issues, plus it was working before. Any help much appreciated. Thanks <?php $product_code = mysqli_real_escape_string($conn, $_POST['product_code']); $product_name = mysqli_real_escape_string($conn, $_POST['product_name']); $category = mysqli_real_escape_string($conn, $_POST['category']); $filter = mysqli_real_escape_string($conn, $_POST['filter']); $description = mysqli_real_escape_string($conn, $_POST['description']); $specification = mysqli_real_escape_string($conn, $_POST['specification']); $price = mysqli_real_escape_string($conn, $_POST['price']); $target_dir = "../images/products/"; if (!isset ($_FILES["img1"]["name"])) { $target_file1 = NULL; } else { if (!empty($_FILES["img1"]["name"])) { $target_file1 = $target_dir . basename($_FILES["img1"]["name"]); } else { $target_file1 = NULL; } } if (!isset ($_FILES["img2"]["name"])) { $target_file2 = NULL; } else { if (!empty($_FILES["img2"]["name"])) { $target_file2 = $target_dir . basename($_FILES["img2"]["name"]); } else { $target_file2 = NULL; } } if (!isset ($_FILES["img3"]["name"])) { $target_file3 = NULL; } else { if (!empty($_FILES["img3"]["name"])) { $target_file3 = $target_dir . basename($_FILES["img3"]["name"]); } else { $target_file3 = NULL; } } if (!isset ($_FILES["img4"]["name"])) { $target_file4 = NULL; } else { if (!empty($_FILES["img4"]["name"])) { $target_file4 = $target_dir . basename($_FILES["img4"]["name"]); } else { $target_file4 = NULL; } } $uploadOk = 1; $imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION)); $imageFileType2= strtolower(pathinfo($target_file2,PATHINFO_EXTENSION)); $imageFileType3 = strtolower(pathinfo($target_file3,PATHINFO_EXTENSION)); $imageFileType4 = strtolower(pathinfo($target_file4,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check1 = getimagesize($_FILES["img1"]["tmp_name"]); $check2 = getimagesize($_FILES["img2"]["tmp_name"]); $check3 = getimagesize($_FILES["img3"]["tmp_name"]); $check4 = getimagesize($_FILES["img4"]["tmp_name"]); if($check1 !== false) { echo "File is an image - " . $check1["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file1)) { echo "Sorry, image one already exists."; $uploadOk = 0; } if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg" && $imageFileType1 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1."; $uploadOk = 0; } if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image one."; } } echo '<br />'; if($check2 !== false) { echo "File is an image - " . $check2["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file2)) { echo "Sorry, image two already exists."; $uploadOk = 0; } if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg" && $imageFileType2 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img2."; $uploadOk = 0; } if (isset ($target_file2)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img2"]["tmp_name"], $target_file2)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image two."; } } } echo '<br />'; if($check3 !== false) { echo "File is an image - " . $check3["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file3)) { echo "Sorry, image three already exists."; $uploadOk = 0; } if($imageFileType3 != "jpg" && $imageFileType3 != "png" && $imageFileType3 != "jpeg" && $imageFileType3 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img3."; $uploadOk = 0; } if (isset ($target_file3)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img3"]["tmp_name"], $target_file3)) { echo "The file ". htmlspecialchars( basename( $_FILES["img3"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image three."; } } } echo '<br />'; if($check4 !== false) { echo "File is an image - " . $check4["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file4)) { echo "Sorry, image four already exists."; $uploadOk = 0; } if($imageFileType4 != "jpg" && $imageFileType4 != "png" && $imageFileType4 != "jpeg" && $imageFileType4 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img4."; $uploadOk = 0; } if (isset ($target_file4)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img4"]["tmp_name"], $target_file4)) { echo "The file ". htmlspecialchars( basename( $_FILES["img4"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image four."; } } } } echo '<br />'; $image1 = basename($target_file1); $image2 = basename($target_file2); $image3 = basename($target_file3); $image4 = basename($target_file4); // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')"; if (mysqli_query($conn, $sql)) { echo "Product Added successfully, Now on to the Sizes"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } ?>
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, I'm planning on making a website where people are able to upload files and directly link to them. Ideally, I want to keep the same file names that the people use when they upload the file. I was planning on keeping the directory that stored all of the files outside of the www directory and disable execute permissions. However, how would I avoid file overwriting with the same file name? Good Evening, If anyone could help with this little problem be much appreciated. what i'm trying to do is using a drop down menu select a folder name which is stored in a database table.. then taking that folder name and upload various files to that specified folder. There's probably an easier way to do this but i've searched google argggh.. The first part of code is the php to grab the folder names and the file selection form Code: [Select] <?php include("connection.php"); $sql="SELECT id, name FROM gallery"; $result=mysql_query($sql); $options=""; while ($row=mysql_fetch_array($result)) { $id=$row["id"]; $thing=$row["name"]; $options.="<OPTION VALUE=\"$id\">".$thing ; } ?> <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form action="postFiles.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td><strong>multiple Files Upload </strong></td> </tr> <td><SELECT NAME=thing> <OPTION VALUE=0>Choose <?=$options?> </SELECT> </td> <tr> <td>Select file <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <td>Select file <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <td>Select file <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <td align="center"><input type="submit" name="Submit" value="Upload" /></td> </tr> </table> </td> </form> </tr> </table> The second part of the code below is the php code to upload those files, the problem being how do i specify the upload destination using the drop down in the previous form (instead of UPLOAD) which it is default set to Code: [Select] <?php //set where you want to store files //in this example we keep file in folder upload //$HTTP_POST_FILES['ufile']['name']; = upload file name //for example upload file name cartoon.gif . $path will be upload/cartoon.gif $path1= "upload".$HTTP_POST_FILES['ufile']['name'][0]; $path2= "upload".$HTTP_POST_FILES['ufile']['name'][1]; $path3= "upload".$HTTP_POST_FILES['ufile']['name'][2]; //copy file to where you want to store file copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1); copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2); copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3); //$HTTP_POST_FILES['ufile']['name'] = file name //$HTTP_POST_FILES['ufile']['size'] = file size //$HTTP_POST_FILES['ufile']['type'] = type of file echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>"; echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]."<BR/>"; echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>"; echo "<img src=\"$path1\" width=\"150\" height=\"150\">"; echo "<P>"; echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>"; echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>"; echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>"; echo "<img src=\"$path2\" width=\"150\" height=\"150\">"; echo "<P>"; echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>"; echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>"; echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>"; echo "<img src=\"$path3\" width=\"150\" height=\"150\">"; /////////////////////////////////////////////////////// // Use this code to display the error or success. $filesize1=$HTTP_POST_FILES['ufile']['size'][0]; $filesize2=$HTTP_POST_FILES['ufile']['size'][1]; $filesize3=$HTTP_POST_FILES['ufile']['size'][2]; if($filesize1 && $filesize2 && $filesize3 != 0) { echo "We have recieved your files"; } else { echo "ERROR....."; } ////////////////////////////////////////////// // What files that have a problem? (if found) if($filesize1==0) { echo "There're something error in your first file"; echo "<BR />"; } if($filesize2==0) { echo "There're something error in your second file"; echo "<BR />"; } if($filesize3==0) { echo "There're something error in your third file"; echo "<BR />"; } ?> Thanks in advance for any help if you need to see a live version of these files i can provide a link |