PHP - Multiple Upload Form Not Uploading!
Hi,
I have been trying to create a site where you can list multiple items with a picture for each but I can't get the upload form working. Here's what I've got: <?php include "/home/a9653716/public_html/header.inc"; ?> <body> <table border="0" width="100%"><tr> <td valign="top" width="800"> <?php echo "<div id='content'>"; echo "<h2 div id='title'>"; echo "Create a listing"; echo "</h2>"; //////content////////////////////////// if($_SESSION['uid']){ $id = mss($_POST['id']); $no_w =($_POST['want']); $no_o =($_POST['offer']); $wantbtn = ($_POST['addwantbtn']); $offerbtn = ($_POST['addofferbtn']); if ($wantbtn) echo "Want <br />"; $no_want = ($_POST['no_want']); $no_offer = ($_POST['no_offer']); if (!$no_w){ if ($no_want){ $no_w = $no_want; }else $no_w = 3; } if (!$no_o){ if ($no_offer){ $no_o = $no_offer; }else $no_o = 3; } if ($no_o > 20){ $no_o = 20; } if ($no_w > 20){ $no_w = 20; } $offerid = 1; $wantid = 1; $addofferlimit = 20 - $no_o + 1; $addwantlimit = 20 - $no_w + 1; $addoffer = 1; $addwant = 1; $addmorewants = ($_POST['addmorewants']); $addmoreoffers = ($_POST['addmoreoffers']); if ($wantbtn){ $no_w = $addmorewants; } if ($offerbtn){ $no_o = $addmoreoffers; } if ($id) { $sql = "SELECT * FROM `item_sub_cats` WHERE `id`='" . $id . "'"; $res = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($res) == 0) { echo "The category you are trying to create a listing on, does not exist!\n"; } else { $row1 = mysql_fetch_assoc($res); if (!$_POST['submit']) { echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n"; echo "<form method=\"post\" action=\"./create_listing.php\">\n"; echo "<tr><td>Sub Category</td><td><select name=\"cat\">\n"; $sql2 = "SELECT * FROM `item_cats`"; $res2 = mysql_query($sql2); while ($row = mysql_fetch_assoc($res2)) { $sql3 = "SELECT * FROM `item_sub_cats` WHERE `cid`='" . $row['id'] . "'"; $res3 = mysql_query($sql3) or die(mysql_error()); echo "<option value=\"0\">" . $row['name'] . "</option>\n"; while ($row2 = mysql_fetch_assoc($res3)) { $selected = ($row2['id'] == $id) ? " SELECTED" : ""; echo "<option value=\"" . $row2['id'] . "\"" . $selected . "> " . $row2['name'] . "</option>\n"; } } echo "</select></td></tr>\n"; echo "<tr><td>Listing Title</td><td><input type=\"text\" name=\"title\" size=\"53\"></td></tr>\n"; ?> <script>edToolbar('message'); </script> <?php echo "<tr><th colspan='2'><b>What you have to offer!</b><br /><br />Change to <select name='addmoreoffers'>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addofferbtn'><br /></th></tr>"; //offer while loop// while ($offerid <= $no_o){ echo "<tr><td>Item $offerid</td><td><input type='textbox' value='title' size='40' name='offer$offerid'> <input type='textbox' value='pts' size='7' name='offer" . $offerid . "pts'></td></tr>"; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='offer" . $offerid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='offer" . $offerid . "img'></td></tr>"; $offerid ++; } //end offer while loop// //want while loop// echo "<tr><th colspan='2'><b>What you want!</b><br /><br />Change to <select>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addwantbtn'><br /></th></tr>"; while ($wantid <= $no_w){ echo "<tr><td>Item $wantid</td><td><input type='textbox' size='40' value='title' name='want" . $wantid . "title'> <input type='textbox' value='pts' size='7' name='want" . $wantid . "pts'></td></tr>"; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='want" . $wantid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='want" . $wantid . "img'></td></tr>"; $wantid ++; } //end want while loop// echo "<tr><td>Other Details</td><th colspan='2'><textarea cols='50' rows='10' id=\"message\" name=\"message\"></textarea></th></tr>\n"; echo "<tr><td colspan=\"2\" align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Create Listing\"></td></tr>\n"; echo "</form></table>\n"; } else { $cat = mss($_POST['cat']); $title = mss($_POST['title']); $details = mss($_POST['message']); if ($cat && $title && $details) { $sql = "SELECT * FROM `item_sub_cats` WHERE `id`='" . $cat . "'"; $res = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($res) == 0) { echo "This sub category does not exist!\n"; } else { $row = mysql_fetch_assoc($res); if (strlen($title) < 3 || strlen($title) > 32) { echo "The title must be between 3 and 32 characters!\n"; } else { if (strlen($details) < 3 || strlen($details) > 10000) { echo "The message must be between 3 and 10,000 characters!\n"; } else { $date = date("m-d-y") . " at " . date("h:i:s"); $time = time(); $sql2 = "INSERT INTO `listing_topics` (`cid`,`title`,`uid`,`date`,`time`,`message`,) VALUES('" . $cat . "','" . $title . "','" . $_SESSION['uid'] . "','" . $date . "','" . $time . "','" . $details . "')"; $res2 = mysql_query($sql2) or die(mysql_error()); $tid = mysql_insert_id(); topic_go($tid); } } } } else { } } } } else { if (!$_POST['submit']) { echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n"; echo "<form method=\"post\" action=\"./create_listing.php\">\n"; echo "<tr><td>Sub Category</td><td><select name=\"cat\">\n"; $sql2 = "SELECT * FROM `item_cats`"; $res2 = mysql_query($sql2) or die(mysql_error()); while ($row = mysql_fetch_assoc($res2)) { $sql3 = "SELECT * FROM `item_sub_cats` WHERE `cid`='" . $row['id'] . "'"; $res3 = mysql_query($sql3) or die(mysql_error()); echo "<option value=\"0\">" . $row['name'] . "</option>\n"; while ($row2 = mysql_fetch_assoc($res3)) { $selected = ($row2['id'] == $id) ? " SELECTED" : ""; echo "<option value=\"" . $row2['id'] . "\"" . $selected . "> " . $row2['name'] . "</option>\n"; } } echo "</select></td></tr>\n"; echo "<tr><td>Listing Title</td><td><input type=\"text\" name=\"title\" size=\"53\"></td></tr>\n"; ?> <script>edToolbar('message'); </script> <?php echo "<tr><th colspan='2'><b>What you have to offer!</b><br /><br />Change to <select name='addmoreoffers'>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addofferbtn'><br /></th></tr>"; //offer while loop// while ($offerid <= $no_o){ $offername = "offer" . "$offerid"; echo "<tr><td>Item $offerid</td><td><input type='textbox' value='title' size='40' name='$offername'> <input type='textbox' value='pts' size='7' name='offer" . $offerid . "pts'></td></tr>"; echo $offername; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='offer" . $offerid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='offer" . $offerid . "img'></td></tr>"; $offerid ++; } //end offer while loop// //want while loop// echo "<tr><th colspan='2'><b>What you want!</b><br /><br />Change to <select name='addmorewants'>"; echo "<option>1</option>"; echo "<option>2</option>"; echo "<option>3</option>"; echo "<option>4</option>"; echo "<option>5</option>"; echo "<option>6</option>"; echo "<option>7</option>"; echo "<option>8</option>"; echo "<option>9</option>"; echo "<option>10</option>"; echo "<option>11</option>"; echo "<option>12</option>"; echo "<option>13</option>"; echo "<option>14</option>"; echo "<option>15</option>"; echo "<option>16</option>"; echo "<option>17</option>"; echo "<option>18</option>"; echo "<option>19</option>"; echo "<option>20</option>"; echo "</select> item(s) <input type='submit' value='Go' name='addwantbtn'><br /></th></tr>"; while ($wantid <= $no_w){ $wantname = "want" . "$wantid"; echo "<tr><td>Item $wantid</td><td><input type='textbox' size='40' value='title' name='$wantname'> <input type='textbox' value='pts' size='7' name='want" . $wantid . "pts'></td></tr>"; echo "<tr><td></td><th colspan='2'><textarea cols='37' rows='5' name='want" . $wantid . "desc'></textarea></th></tr>"; echo "<tr><td></td><td><input type='file' size='27' name='want" . $wantid . "img'></td></tr>"; $wantid ++; } //end want while loop// echo "<tr><td>Other Details</td><th colspan='2'><textarea cols='50' rows='10' id=\"message\" name=\"message\"></textarea></th></tr>\n"; echo "<tr><td colspan=\"2\" align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Create Listing\"></td></tr>\n"; echo "<input type='hidden' name='no_offer' value='$no_o'>"; echo "<input type='hidden' name='no_want' value='$no_w'>"; echo "</form></table>\n"; } else { $cat = mss($_POST['cat']); $title = mss($_POST['title']); $details = mss($_POST['message']); $o_title_count = 1; $filled_o = 1; $offer_no_values=1; $w_title_count = 1; $filled_w = 1; $want_no_values=1; while ($filled_o && $filled_o != "title"){ $o_title_count = "offer" . "$offer_no_values"; $filled_o = ($_POST["$o_title_count"]); $offer_no_values++; } $offer_no_values=$offer_no_values-2; echo "Number of offer titles:" . $offer_no_values . "<br />"; while ($filled_w && $filled_w != "title"){ $w_title_count = "want" . "$want_no_values"; $filled_w = ($_POST["$w_title_count"]); $want_no_values++; } $want_no_values=$want_no_values-2; echo "number of want titles:" . $want_no_values . "<br />"; echo "cat: " . $cat . "<br />"; echo "title: " . $title . "<br />"; echo "message: " . $details . "<br />"; echo "want_no_values: " . $want_no_values . "<br />"; echo "offer_no_values: " . $offer_no_values . "<br />"; if ($cat && $title && ($want_no_values >= 1) && ($offer_no_values >= 1)) { ////////////////////////////////////////////////////// ////////////////////want construct//////////////////// ////////////////////////////////////////////////////// $x=1; while ($x <= $want_no_values){ $w_points = "want" . $x . "pts"; $w_desc = "want" . $x . "desc"; $w_image = "want" . $x . "img"; if ($w_image){ $w_img_name = $_FILES['want1img']['name']; $w_img_type = $_FILES['$w_image']['type']; $w_img_size = $_FILES['$w_image']['size']; $w_img_tmpname = $_FILES['$w_image']['tmp_name']; $w_img_ext = substr($w_img_name, strpos($w_img_name, '.')); echo "w name:" . $w_img_name . "<br />"; print_r ($_FILES['want1img']); } if ($w_img_name){ move_uploaded_file($w_img_tmpname, "images/listings/$username" . "-" . "$w_img_name" . "-" . "$w_img_size" . "$ext") or die(mysql_error()); $w_image = "$username" . "-" . "$w_img_name" . "-" . "$w_img_size" . "$ext"; } echo $w_points; $w_item_name = ($_POST["want$x"]); $w_item_pts = ($_POST["$w_points"]); $w_item_desc = ($_POST["$w_desc"]); $want_item = "<tr><td width='25'></td><th colspan='3'><b>" . $w_item_name . "</b> - " . $w_item_pts . "pts</th></tr> <tr><td width='25'></td><td width='25'></td><th colspan='2'>" . $w_item_desc . $w_image . "</th></tr>"; $want_items = $want_items . $want_item; $x++; } $want_desc = "<table> <tr><th colspan='3'><h3>What I want!</h3></th></tr>" . $want_items . "</table>"; ////////////////////////////////////////////////////// ////////////////////offer construct/////////////////// ////////////////////////////////////////////////////// $x=1; while ($x <= $offer_no_values){ $o_points = "offer" . $x . "pts"; $o_desc = "offer" . $x . "desc"; echo $w_points; $o_item_name = ($_POST["offer$x"]); $o_item_pts = ($_POST["$o_points"]); $o_item_desc = ($_POST["$o_desc"]); $offer_item = "<tr><td width='25'></td><th colspan='3'><b>" . $o_item_name . "</b> - " . $o_item_pts . "pts</th></tr> <tr><td width='25'></td><td width='25'></td><th colspan='2'>" . $o_item_desc . "</th></tr>"; $offer_items = $offer_items . $offer_item; $x++; } $offer_desc = "<table> <tr><th colspan='3'><h3>What I offer!</h3></th></tr>" . $offer_items . "</table>"; $desc=$want_desc . $offer_desc; echo $desc; } else { echo "Please supply all the fields!\n"; } } } } else echo "You must be logged in to see this page!"; ?> </td><td width="250"> <?php include("sidebar.inc"); ?> </td> </table> </body> </html> <?php include("footer.inc"); ?> I know it's very messy, I'll probably end up rewriting it but this is what I get after supplying the right fields and uploading an image for the want section: Code: [Select] Number of offer titles:1 number of want titles:1 cat: 1 title: This is the title message: None still testing it! want_no_values: 1 offer_no_values: 1 w img name: want1ptswant1pts The only bit that is of any use is the name section: Code: [Select] w img name: Nothing is recieved and the file is not uploaded!! I probably have missed something out but I am very new to php so please help!! Thanks Cameron Similar TutorialsI have been spending the majority of this week figuring out why my files are not showing up at my upload location that I set up in my newly created simple upload form. It just seems like php doesn't like me at all. Here is what my code looks like below. Code: [Select] <?php if (move_uploaded_file($_FILES['thefile']['name'], $upload_file)) $destination = "/www/zymichost.com/m/t/l/mtlproductions/htdocs/"; $upload_file = $destination . basename($_FILES['thefile']['name']);{ echo "Your file has been uploaded successfully!"; }/* else { echo "Your file did not upload successfully. Check to make sure your file meets the requirements and then try again."; print_r($_FILES);}*/?> I have the orange marked areas commented out due to the unexpected T_ELSE error thing. What do I do to get my files to show up at my upload location when I use my upload form? Thanks! Dear all, I have a problem that I need to be helped with using one form and storing the images in database. I would like to upload multiple images with same title from "title" field. Can somebody help me with this? <?php $db_host = 'localhost'; // don't forget to change $db_user = 'mysql-user'; $db_pwd = 'mysql-password'; $database = 'test'; $table = 'ae_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)';// use (empty title) string if ($_POST['password'] != $password) // cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['photo'])) { @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']); // Get image type. // We use @ to omit errors if ($imtype == 3) // cheking image type $ext="png"; // to use it later in HTTP headers elseif ($imtype == 2) $ext="jpeg"; elseif ($imtype == 1) $ext="gif"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: image uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Photo deleted'; } } } elseif (isset($_GET['show'])) { $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $image_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $image_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } ?> <html><head> <title>MySQL Blob Image Gallery Example</title> </head> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?> <br> <a href="<?=$PHP_SELF?>">reload page</a> <!-- I've added reloading link, because refreshing POST queries is not good idea --> </p> <?php } ?> <h1>Blob image gallery</h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else { echo '<ul>'; while(list($id, $image_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$image_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> </form> <h2>Upload new image:</h2> <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br> <input type="text" name="title" id="title" size="64"><br><br> <label for="photo">Photo:</label><br> <input type="file" name="photo" id="photo"><br><br> <label for="password">Password:</label><br> <input type="password" name="password" id="password"><br><br> <input type="submit" value="upload"> </form> </body> </html> Hey, been trying to make a form to upload an image to the server and also email the image as attachment. After nearly a week I managed to make it work. Only some validation needs to be done. My next step is to make it work for multiple files, ie. 5. The form will have 5 boxes to upload images and no more. I have tried a few different things with for loops ( ie for $i=0; $i<5; $i++ {...} ) but no luck. I can't think of any solution of a loop to upload multiple files and then email multiple attachment as my code. The code is: <?php session_start(); $imagename1 = $_FILES["uploadFile1"]["name"]; $_SESSION['imagename1'] = $imagename1; $imagename1 = $_SESSION['imagename1']; $imagetype1 = $_SESSION['imagetype1']; $imagesize1 = $_SESSION['imagesize1']; $imagetemp1 = $_SESSION['imagetemp1']; $thankyouurl = 'thankyou.php' ; $errorurl = 'error.php' ; $http_referrer = getenv( "HTTP_REFERER" ); $http_agent = getenv( "HTTP_USER_AGENT" ); $domain = $_SERVER['REMOTE_ADDR']; $filename = $_SESSION['uploadFilename']; if(isset($_POST['send'])) { $fp = fopen($imagetemp1, "rb"); $file = fread($fp, $imagesize1); $file = chunk_split(base64_encode($file)); $num = md5(time()); fclose($fp); // UPLOAD FILE // possible PHP upload errors $errors = array(1 => 'php.ini max file size exceeded', 2 => 'html form max file size exceeded', 3 => 'file upload was only partial', 4 => 'no file was attached'); // check the upload form was actually submitted else print form isset($_POST['send']) or error('the upload form is neaded', $uploadForm); // check for standard uploading errors ($_FILES[$fieldname1]['error'] == 0) or error($errors[$_FILES[$fieldname1]['error']], $uploadForm); // check that the file we are working on really was an HTTP upload @is_uploaded_file($_FILES[$fieldname1]['tmp_name']) or error('not an HTTP upload', $uploadForm); // validation... since this is an image upload script we // should run a check to make sure the upload is an image @getimagesize($_FILES[$fieldname1]['tmp_name']) or error('only image uploads are allowed', $uploadForm); // make a unique filename for the uploaded file and check it is // not taken... if it is keep trying until we find a vacant one $now = date("y-m-d_H-i-s", time()); while(file_exists($uploadFilename = $uploadsDirectory.$now.'_'.$_FILES[$fieldname1]['name'])) { $now++; } // now let's move the file to its final and allocate it with the new filename @move_uploaded_file($_FILES[$fieldname1]['tmp_name'] , $uploadFilename) or error('receiving directory insuffiecient permission', $uploadForm); $from= 'youremail@server.co.uk'; $emailTo = 'mail@hotmail.com'; $subject = 'Quote Form'; $body = "equipment_type: $equipment_type \n\nModel: $Model \n\nMake: $Make \n\nModelNumber: $ModelNumber"; $fp = $_SESSION['fp']; $file = $_SESSION['file']; $num = "==Multipart_Boundary_x{$semi_rand}x".$_SESSION['num']; $headers = 'From: Name <'.$from.'>' . "\r\n" . 'Reply-To: ' . $emailTo; //Normal headers $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: multipart/mixed; "; $headers .= "boundary=".$num."\r\n"; $headers .= "--$num\r\n"; // This two steps to help avoid spam $headers .= "Message-ID: <".gettimeofday()." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n"; $headers .= "X-Mailer: PHP v".phpversion()."\r\n"; // With message $headers .= "Content-Type: text/html; charset=iso-8859-1\r\n"; $headers .= "Content-Transfer-Encoding: 8bit\r\n"; $headers .= "".$body."\n"; $headers .= "--".$num."\n"; // Attachment headers $headers .= "Content-Type:".$imagetype1." "; $headers .= "name=\"".$imagename1."\"r\n"; $headers .= "Content-Transfer-Encoding: base64\r\n"; $headers .= "Content-Disposition: attachment; "; $headers .= "filename=\"".$imagename1."\"\r\n\n"; $headers .= "".$file."\r\n"; $headers .= "--".$num."--"; mail($emailTo, $subject, $body, $headers); header( "Location: $thankyouurl" ); } ?> the form is like this Code: [Select] <input name="uploadFile1" id="uploadFile1" value="" class="file" type="file"/>can anyone suggest anything please? how can I form the for statement? much appreciated Hey guys. I'm using this script to handle file (picture) uploads at the moment, and it works fine. Problem is though, I need to changeit to a multiple upload form (with 10 uploads per submit) and I dont know how to do it. I think ... I need to change this "<input type="file" name="image" >" to an array ... and put a "for each" loop or something somewhere ... but I really don't know what I am doing. Can someone please help? Thanks Gem <?php include ("includes/dbconnect120-gem.php"); //define a maxim size for the uploaded images define ("MAX_SIZE","500"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","150"); define ("HEIGHT","100"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded. $errors=0; if(isset($_POST['submit1']) && !$errors) { $sqlalbum="INSERT INTO album (album_name) VALUES ('$_POST[newalbumname]')"; mysql_query($sqlalbum) or die ('Error, album_query failed : ' . mysql_error()); } // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message //and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="uploads/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='uploads/thumbs/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters //the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { $album = $_POST['album']; $query = "INSERT INTO upload (name, path, album_id, thumbpath ) ". "VALUES ('$image_name', '$newname' , '$album', '$thumb_name')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form name="newalbum" method="post" action=""> <input name="newalbumname" type="text" size="30" maxlength="30" value="<?php echo $newalbumname; ?>" /> <input type="submit" name="submit1" value="Create Album" /> </form> <br /> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><select name="album"> <option value="select" selected="selected" >-Albums-</option> <?php $asql="select * from album order by album_id DESC"; $aresult=mysql_query($asql) or die(mysql_error());; while($arow=mysql_fetch_array($aresult)) { $album_id=$arow['album_id']; $album_name=$arow['album_name']; ?> <option value="<?php echo $album_id; ?>"><?php echo $album_name; ?></option> <?php } ?> </select> <tr><td><input type="file" name="image" ></td></tr> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr> </table> </form> </body> </html> Hello, this question was already answered on this form but the answer was deleted by admin a year or so ago. anyway, I have an edit items page with multiple images and I do not want to have to relocate all of the images manually but if I do not then an empty variable is passed to mysql, thus deleting my image. What do I need to know to write a code that will not pass an empty variable to my table? Do I use sprint? I am VERY new to PHP, but I am trying to adapt code from http://www.4wordsystems.com/php_image_resize.php to work with multiple images. Can any please help? I know I need to place it in a loop of some kind, but I don't know how to write the code for that. Here is the code: HTML FORM CODE: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data" > <input type="file" name="uploadfile"/> <input type="submit"/> </form> upload.php CODE: Code: [Select] <?php // This is the temporary file created by PHP $uploadedfile = $_FILES['uploadfile']['tmp_name']; // Create an Image from it so we can do the resize $src = imagecreatefromjpeg($uploadedfile); // Capture the original size of the uploaded image list($width,$height)=getimagesize($uploadedfile); // For our purposes, I have resized the image to be // 600 pixels wide, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max width other than // 600, simply change the $newwidth variable $newwidth=600; $newheight=($height/$width)*600; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); // For our purposes, I have resized the image to be // 150 pixels high, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max height other than // 150, simply change the $newheight variable $newheight=150; $newwidth=($width/$height)*150; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/thumb_". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request // has completed. echo "Successfully Uploaded: <img src='".$filename."'>"; ?>
I have a hopefully small issue on a form submitting data to the mysql database table and email. The email side works fine as does the adding the data to the database table but if I upload two files, it stores the support ticket twice in the database table where as I want to store just once and the files be stored as a array in the database table. I got the code from the link https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
<?php require_once "registerconfig.php"; if (isset($_POST['submit'])) { // File upload configuration $targetDir = "support-ticket-images/"; $allowTypes = array('pdf','doc','docx','jpg','png','jpeg','gif'); $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; // Escape user inputs for security $ticket_subject = htmlentities($_POST['ticket_subject'], ENT_QUOTES); $ticket_message = strip_tags($_POST['ticket_message'], ENT_QUOTES); $ticket_status ='PENDING SUPPORT'; $username = htmlentities($_SESSION["user_name"], ENT_QUOTES); $user_id = htmlentities($_SESSION["user_id"], ENT_QUOTES); $fileNames = array_filter($_FILES['files']['name']); if(!empty($fileNames)){ foreach($_FILES['files']['name'] as $key=>$val){ // File upload path $fileName = basename($_FILES['files']['name'][$key]); $targetFilePath = $targetDir . $fileName; // Check whether file type is valid $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ // Image db insert sql $insertValuesSQL .= "('".$ticket_subject."','".$ticket_message."','".$fileName."','".$ticket_status."','".$username."', '".$user_id."'),"; }else{ $errorUpload .= $_FILES['files']['name'][$key].' | '; } }else{ $errorUploadType .= $_FILES['files']['name'][$key].' | '; } } if(!empty($insertValuesSQL)){ $insertValuesSQL = trim($insertValuesSQL, ','); // Insert image file name into database $insert = $link->query("INSERT INTO DB TABLE NAME (ticket_subject, ticket_message, file_name, ticket_status, user_name, user_id) VALUES $insertValuesSQL"); if($insert){ $to = "emailaddress"; $subject = "A new support ticket has been submitted"; $message = " <strong>$username</strong> has just created a support ticket, below is the support ticket <br /><br /> <u>Support Ticket Details</u> <br /><br> <strong>Support Ticket Subject</strong>: $ticket_subject <br/><br><strong>Support Ticket Message</strong>: $ticket_message <p><strong><u>Support Ticket Files</u></strong> <br> <img src='$fileName'> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // More headers $headers .= 'From: <noreply@emailaddress>' . "\r\n"; $mail=mail($to,$subject,$message,$headers); $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; header("location: support-ticket-confirmation?user=$username"); }else{ $statusMsg = "Sorry, there was an error uploading your file."; } } }else{ $statusMsg = 'Please select files to upload.'; } // Display status message echo $statusMsg; } ?> The structure of the db table column is file_name, VARCHAR(255), latin1_swedish_ci, NOT NULL Hello,
I'm developing one website for a real-estate agency. I have a html form that is used to submit property details, There is multiple form inputs and also I need to upload multiple property images using Dropzone JS multiple image upload. Here I'm validating form inputs using jQuery Validation library. Validation works perfect and data Is being to posted to php file called submit_property_data.php. But when I implement the Dropzone JS image upload its not working.
JS File (property-submit.js)
$('document').ready(function() { $("#notification-property").hide(); /* handling form validation */ $("#property-form").validate({ rules: { prop_title: "required", prop_price: { required: true, digits: true }, prop_area: { required: true, digits: true }, prop_address: "required", prop_message: { required: true, minlength: 10, maxlength: 2000 }, prop_owner_name: "required", prop_owner_email: { required: true, email: true }, prop_owner_phone: { required: true, digits: true }, }, messages: { 'prop_title': { required: "Please enter title for your property" }, prop_price: { required: "Please enter price of your property", digits: "Please enter price in digits (AED)" }, prop_area: "Please enter Sqft of your property", prop_address: "Please enter address of your property", prop_message: { required: "Please enter detailed Information", minlength: "Please enter something about your property in 50 - 20000 characters", maxlength: "Please enter something about your property in 50 - 20000 characters" }, prop_owner_name: "Please enter your name", prop_owner_email: { required: "Please enter your email address", email: "Please enter valid email address" }, prop_owner_phone: { required: "Please enter your phone number", digits: "Please enter valid phone number" }, }, submitHandler: submitPropertyForm }); /* Handling login functionality */ function submitPropertyForm() { var data = $("#property-form").serialize(); $.ajax({ type: 'POST', url: 'submit_property_data.php', data: data, beforeSend: function() { $("#submit-button").html('<span class="glyphicon glyphicon-transfer"></span> Submiting ...'); }, success: function(response) { if (response == "ok") { console.log(1); document.getElementById("property-form").reset(); $("#notification-property").html('<b> ' + response + ' !</b>').show(); //setTimeout(' window.location.href = "dashboard.php"; ',4000); } else { $("#notification-property").fadeIn(1000, function() { $("#notification-property").html('<b>' + response + ' !</b>').fadeOut(); $("#submit-button").html(' Send'); }); } }, complete:function(){ $('body, html').animate({scrollTop:$('form').offset().top}, 'slow'); } }); return false; } $("#submit-button").bind('click', function() { if ( $("#property-form").valid() ) { submitPropertyForm(); } else { console.log('form invalid'); } }) Dropzone.autoDiscover = false; $(function () { $("div#myDropzone").dropzone({ url: 'submit_property_data.php', addRemoveLinks: true, maxFiles:11, uploadMultiple: true, autoProcessQueue: false, parallelUploads: 10, init: function () { var myDropzone = this; // Update selector to match your button $("#submit-button").click(function (e) { e.preventDefault(); myDropzone.processQueue(); }); this.on('sending', function(file, xhr, formData) { // Append all form inputs to the formData Dropzone will POST var data = $('#property-form').serializeArray(); $.each(data, function(key, el) { formData.append(el.name, el.value); }); }); this.on("success", function(file, responseText) { alert(responseText); }); }, }); }); });
HTML File (submit-property.php)
<html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script> !-- Submit Property start --> <div class="content-area-7 submit-property"> <div class="container"> <div class="row"> <div class="col-md-12"> <!-- <div id="error_message" class="notification-box"></div> --> </div> <div id="notification-property" class="notification-box">sd</div> <div class="col-md-12"> <div class="submit-address"> <form name = "property-form" method="post" id="property-form"> <div class="main-title-2"> <h1><span>Tell Me</span> Something About Your Property</h1> </div> <div class="search-contents-sidebar mb-30"> <div class="form-group"> <label>Property Title</label> <input class="input-text" name="prop_title" id="prop_title" placeholder="Property Title"> </div> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Status</label> <select class="selectpicker search-fields" id="prop_status" name="prop_status"> <option value="Sale">For Sale</option> <option value="Rent">For Rent</option> </select> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Type</label> <select class="selectpicker search-fields" id="prop_title" name="prop_type"> <option value="Modern">Modern</option> <option value="Traditional">Traditional</option> <option value="Arabic">Arabic</option> </select> </div> </div> </div> <div class="row"> <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Price (Dirham)</label> <input class="input-text" name="prop_price" id="prop_price" placeholder="AED"> </div> </div> <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Sqft</label> <input class="input-text" name="prop_area" id="prop_area" placeholder="SqFt"> </div> </div> <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Bed Rooms</label> <select class="selectpicker search-fields" name="prop_rooms" id="prop_rooms"> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> <!-- <div class="col-md-3 col-sm-6"> <div class="form-group"> <label>Bathroom</label> <select class="selectpicker search-fields" name="1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> --> </div> </div> <div class="main-title-2"> <h1><span>Location</span></h1> </div> <div class="row mb-30 "> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Address</label> <input class="input-text" id="prop_address" name="prop_address" placeholder="Address"> </div> </div> </div> <div class="main-title-2"> <h1><span>Upload</span> Photos Of Villa </h1> </div> <div id="myDropzone" class="dropzone dropzone-design mb-10"> <div class="dz-default dz-message" data=""><span>Drop files here to upload</span></div> </div> <div class="main-title-2"> <h1><span>Detailed</span> Information</h1> </div> <div class="row mb-30"> <div class="col-md-12"> <div class="form-group"> <textarea class="input-text" id="prop_message" name="prop_message" placeholder="Detailed Information"></textarea> </div> </div> </div> <!--<div class="row mb-30"> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Building Age <span>(optional)</span></label> <select class="selectpicker search-fields" name="years"> <option>0-1 Years</option> <option>0-5 Years</option> <option>0-10 Years</option> <option>0-20 Years</option> <option>0-40 Years</option> <option>40+Years</option> </select> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Bedrooms (optional)</label> <select class="selectpicker search-fields" name="1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Bathrooms (optional)</label> <select class="selectpicker search-fields" name="1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="col-lg-12"> <label class="margin-t-10">Features (optional)</label> <div class="row"> <div class="col-lg-4 col-sm-4 col-xs-12"> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_parking" name="opt_parking" value="1" type="checkbox"> <label for="checkbox1"> Free Parking </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_air_condition" name="opt_air_condition" value="1" type="checkbox"> <label for="checkbox2"> Air Condition </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_seat" name="opt_seat" value="1" type="checkbox"> <label for="checkbox3"> Places to seat </label> </div> </div> <div class="col-lg-4 col-sm-4 col-xs-12"> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_swimming" name="opt_swimming" value="1" type="checkbox"> <label for="checkbox4"> Swimming Pool </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_laundary" name="opt_laundary" value="1" type="checkbox"> <label for="checkbox5"> Laundry Room </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_window_covering" name="opt_window_covering" value="1" type="checkbox"> <label for="checkbox6"> Window Covering </label> </div> </div> <div class="col-lg-4 col-sm-4 col-xs-12"> <div class="checkbox checkbox-theme checkbox-circle"> <input id="opt_parking" name="opt_parking" value="1" type="checkbox"> <label for="checkbox7"> Central Heating </label> </div> <div class="checkbox checkbox-theme checkbox-circle"> <input id="checkbox8" type="checkbox"> <label for="checkbox8"> Alarm </label> </div> </div> </div> </div> </div>--> <div class="main-title-2"> <h1><span>Contact</span> Details</h1> </div> <div class="row"> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Name</label> <input class="input-text" name="prop_owner_name" id="prop_owner_name" placeholder="Name"> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Email</label> <input class="input-text" name="prop_owner_email" id="prop_owner_email" placeholder="Email"> </div> </div> <div class="col-md-4 col-sm-4"> <div class="form-group"> <label>Contact No</label> <input class="input-text" name="prop_owner_phone" id="prop_owner_phone" placeholder="Phone"> </div> </div> </div> <div class="col-md-12"> <button type="button" name="submit-button" id="submit-button">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> <script src="property-submit.js"></script> <script src="js/dropzone.js"></script> </html>
PHP File (submit_property_data.php)
<?php echo "ok"; require_once("functions.php"); $ds = DIRECTORY_SEPARATOR; //1 $storeFolder = 'villas-images'; $encpt_data = rand(1000,5000); if (!empty($_FILES)) { $tempFile = $_FILES['file']['tmp_name']; //3 $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4 $targetFile = $targetPath.$_FILES['file']['name']; //5 if(move_uploaded_file($tempFile,$targetFile)) { echo '<b>Success</b>'; } } ?>
What I actually need ?
I need to validate the form inputs first & upload the images once the form is valid also I need to post all the inputs to my php file called submit_property_data.php Also I need the image inputs to store into my database.
Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks I 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 How can i edit just one image at on time with a multiple image upload form? I have the images being stored in a folder and the path being stored in MySQL. I also have the files being uploaded with a unique id. My issue is that I want to be able to pass the values of what is already in $name2 $name3 $name4 if I only want to edit $name1. I don't want to have to manually update the 4 images. Here is the PHP: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $uploadDir = 'upload/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if ($fileName != ""){ $filePath = $uploadDir; $fileName = str_replace(" ", "_", $fileName); //Split the name into the base name and extension $pathInfo = pathinfo($fileName); $fileName_base = $pathInfo['fileName']; $fileName_ext = $pathInfo['extension']; //now we re-assemble the file name, sticking the output of uniqid into it //and keep doing this in a loop until we generate a name that //does not already exist (most likely we will get that first try) do { $fileName = $fileName_base . uniqid() . '.' . $fileName_ext; } while (file_exists($filePath.$fileName)); $file_names [] = $fileName; $result = move_uploaded_file($tmpName, $filePath.$fileName); } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[] = $filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i = 0; $i < 4; $i++) { $values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : ''; if($values[$i] != '') { $updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); Code: [Select] <?php if (!isset($_SESSION['user_id'])) { echo '<p class="login">Please <a href="login.php">log in</a> to access this page.</p>'; exit(); } else{ //Echo out the username of member echo('<h3 class="login"> ' . $_SESSION['username'] . '\'s Settings </h3>'); } mysqli_close($dbc); $max_no_img=3; // Maximum number of images value to be set here echo "<form method=post action=upload_project.php enctype='multipart/form-data'>"; echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>"; for($i=1; $i<=$max_no_img; $i++){ echo "<tr><td>images $i</td><td> <input type=file name='userfile[]' class='bginput'></td></tr>"; } echo "<tr><td colspan=2 align=center><input type=submit value='Add image'></td></tr>"; echo "</form> </table>"; function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } for($i=0; $i < 3; $i++) { $ext = findexts ($_FILES['userfile']['name'][$i]) ; $ran = rand () ; $ran2 = $ran."."; $add = "upload/"; $add = $add . $ran2.$ext; $image[$i] = $ran2.$ext ; move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $add); $new_id = $image[$i]++; $pic =$new_id++; $query = "INSERT INTO cycles (large_image1,large_image2,large_image3)". "VALUES ('$ran.$ext','$new_id','$pic')"; mysql_query($query) or die('database Query Error!'); } echo "Successfully uploaded the image"; exit; ?> Hi guys, I've been using this code to try and get image paths to upload to a database and store the image in a file called "upload/" but it doesnt seem to be working. I am also using two tables in my database and need to add into the script the user session id (user_id primary) from the current page and store it into the (user_id foreign) for the cycles tables. thanks I need to be able to upload multiple files with the use of one form. Right now I have support for one file and it works great. I am stuck on what route I should take for times sake and reliability and functionality. Can I run each file on its own through the PHP script to upload the file; I would have to create a loop to run through the script as many times as there are files. OR Do I create new functionality and add the files through the use of an array? This is where I am getting the ARRAY idea: http://www.phpeasystep.com/phptu/2.html This is the PHP code that is submitting the image and uploading to file system. This is what I would use to loop through multiple files if I take the loop method. <? header("location: /classifieds/index.php"); echo '<html><center>'; //first lets upload any files that were selected// $date = date("m/d/y",time()); //check that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 2500000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { //strip off file path for $newname variable so path is not accessible via html// $tempnewname = explode('/', $newname); echo $tempnewname; $newname=$tempnewname[9].'/'.$tempnewname[10]; echo "It's done! The file has been saved as: ".$filename; } else { echo "Error: A problem occurred during file upload!"; } } else { //echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";// $timestampname = str_replace('.jpg', date('j-n-Y_g:i:s').'.jpg', (basename($_FILES['uploaded_file']['name']))); $path = dirname(__FILE__).'/uploads/'; $fullname = $path.$timestampname; //strip off file path for $newname variable so path is not accessible via html// $tempnewname = explode('/', $fullname); $newname=$tempnewname[7].'/'.$tempnewname[8]; $picname=$tempnewname[8]; ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))); } } else { echo "Error: Only .jpg images under 2.5MB are accepted for upload"; } } else { echo "Error: No file uploaded"; } ?> Thanks for hte help -Beemer Hi there, I have a form submitting to a mysql database. It was requested that I put a multiple file upload option on it. So I added the fields to the form and the database and added the upload script to the form processing file (and of course created the folder on the server with proper permissions to upload to). It should upload the file(s) to the folder on the server and insert the filename into the database. I keep getting: HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request. This leads me to believe the upload script isn't working properly. If someone could take a look at it I would be a very happy guy. This is the upload script: (insert.php) Code: [Select] <?php $con = mysql_connect("server","user","pass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("db", $con); $dateSubmitted = date("Y-m-d"); $target = "attachments/"; $target = $target . basename( $_FILES['doc1']['name']); $target = $target . basename( $_FILES['doc2']['name']); $target = $target . basename( $_FILES['doc3']['name']); $target = $target . basename( $_FILES['doc4']['name']); $target = $target . basename( $_FILES['doc5']['name']); $sql="INSERT INTO investments (active, project, inv_amount, account_type, prefix, first_name, last_name, address1, address2, city, province, postal_code, country, phone, email, referral_fee, ref_agent, ship_name, ship_address, ship_city, ship_province, ship_postal, ship_country, notes, dateSubmitted, doc1, doc2, doc3, doc4, doc5) VALUES ('$_POST[active]','$_POST[account_type]','$_POST[project]','$_POST[inv_amount]','$_POST[prefix]','$_POST[prefix]','$_POST[first_name]','$_POST[last_name]','$_POST[address1]', '$_POST[address2]','$_POST[city]','$_POST[province]','$_POST[postal_code]','$_POST[country]','$_POST[phone]','$_POST[email]','$_POST[referral_fee]','$_POST[ref_agent]','$_POST[ship_name]','$_POST[ship_address]','$_POST[ship_city]','$_POST[ship_province]','$_POST[ship_postal]','$_POST[ship_country]','$_POST[notes]','$_POST[dateSubmitted]',$_FILES['doc1']['name'],$_FILES['doc2']['name'],$_FILES['doc3']['name'],$_FILES['doc4']['name'],$_FILES['doc5']['name'])"; //Writes the photo to the server if(move_uploaded_file($_FILES['doc1']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc2']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc3']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc4']['tmp_name'], $target)) if(move_uploaded_file($_FILES['doc5']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } //echo "1 record added"; header("Location: ../forms.php"); mysql_close($con) ?> Thanks in advance. JE Hey! First timer here, please be gentle on me. 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> <title>Leettarin Uploader</title> //<link href="style.css" rel="stylesheet" type="text/css" /> <BODY BACKGROUND="Ready.jpg"> <link rel="shortcut icon" href="xxx/twg/favicon.ico"> </head> <?php ob_start(); define("MAX_COUNT", 10); define("UPLOAD_DIRECTORY", "valokuvat/"); define("MAX_SIZE", 1000000); if(!is_dir(UPLOAD_DIRECTORY)) { mkdir(UPLOAD_DIRECTORY, 0777); } if(file_exists($_FILES['file1']['tmp_name'])) { for($i=1; $i<=MAX_COUNT; $i++) { if($_FILES['file'.$i]['size'] > MAX_SIZE) { echo "Liian iso tiedosto!<br>".MAX_SIZE." on raja"; break; } while(file_exists(UPLOAD_DIRECTORY.$_FILES['file'.$i]['name'])) {$_FILES['file'.$i]['name']="$k".$_FILES['file'.$i]['name']; $k++; } move_uploaded_file($_FILES['file'.$i]['tmp_name'], UPLOAD_DIRECTORY.$_FILES['file'.$i]['name']); echo "xxx/waddap/valokuvat/".$_FILES['file'.$i]['name']; exit(); } } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" ENCTYPE="multipart/form-data"> <INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="102400000"> <?php for($i=1;$i<=MAX_COUNT;$i++) { echo " <b><font style=\"color: #00FFFF;\">$i</font></b> <input type=\"file\" name=\"file".$i."\" size=\"75\"><br>"; } ?> <input type="submit" value="Upload"></form><?php ob_end_flush(); exit; ?> Basically, I want this to also display details concerning EVERY uploaded file. I can fix the text and decoration part later, but for now I'd like to know how to make it display information from every uploaded file upon multi-uploading. Information, as in a simple link to the image will do now just fine. So it kind of would redirect you after an upload process to page where are links to all uploads just done. I can only get it to work with 1st file and evidently other files won't even be uploaded then, hm. Also would appreciate a code for blocking other filetypes but .jpeg, .jpg, .png, .gif and .bmp. I'd highly appreciate help! Anyone know of a script that will allow you to upload a file and converts it to a specified file format? Folder layout: script/ script/videos/mp4/ } script/videos/ogg/ } folders for converted files from uploaded files script/videos/webm/ } script/videos/swf/ } Video player: Code: [Select] <video width="320" height="240" controls="controls"> <source src="script/videos/mp4/<? echo $movie; ?>.mp4" type="video/mp4" /> <source src="script/videos/ogg/ <? echo $movie; ?> .ogg" type="video/ogg" /> <source src="script/videos/webm/ <? echo $movie; ?> .webm" type="video/webm" /> <object data="script/videos/mp4/ <? echo $movie; ?> .mp4" width="320" height="240"> <embed src="script/videos/swf/ <? echo $movie; ?> .swf" width="320" height="240"> Your browser does not support video </embed> </object> </video> I have searched and searched the web for an answer and cannot find one pleas help? 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, i'm trying to create simple form that will also upload only xml data. first, the user will need to upload an xml document only by clicking submit, the data will be posted to the server and the user will be redirected to uploader.php. This PHP file is going to process the form data and do all the work. #upload.php <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <body> <form enctype="multipart/form-data" action="uploader.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="500" /> Please select the correct file that you require to create an XML export. <br/> <label for="uploadfile">Filename:</label> <input name="uploadfile" type="file" size="100"/> <input type="submit" value="Upload File" /> </form> </body> </html> second, i'd like to process the data and post the information to another php document that will parse the xml document. this particular file is not getting past the first if statement. i'm not really seeing why??? #uploader.php <?php //File upload restrictions parameters //Will only restrict to allowing xml documents to be uploaded if ((($_FILES["file"]["type"] == "application /xml") { 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 />"; //Save the uploaded files to a directory //If the file already exists with the same date stamp, do not upload if (file_exists("../upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } //If the file does not exist, create a new entry else { move_uploaded_file($_FILES["file"]["tmp_name"], "../upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "../upload/" . $_FILES["file"]["name"]; } } } //Create an error messag else { echo "This is an invalid file. Please make sure an XML document has been selected to upload. Thanks."; } // make an error handler which will be used if the upload fails function error($error, $location, $seconds = 20) { header("Refresh: $seconds; URL=\"$location\""); echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n". '"http://www.w3.org/TR/html4/strict.dtd">'."\n\n". '<html lang="en">'."\n". ' <head>'."\n". ' <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n". ' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n". ' <title>Upload error</title>'."\n\n". ' </head>'."\n\n". ' <body>'."\n\n". ' <div id="Upload">'."\n\n". ' <h1>Upload failure</h1>'."\n\n". ' <p>An error has occured: '."\n\n". ' <span class="red">' . $error . '...</span>'."\n\n". ' The upload form is reloading</p>'."\n\n". ' </div>'."\n\n". '</html>'; exit; } // end error handler ?> third, once the simple file parses the information.. i'd like to display a dropdown menu that will allow a person to select what entry they'd like to be displayed, namely page to be redirected to. #dropdown.php <?php $drop = $_REQUEST['dropdown']; ?> <html> <body> <form action="results.php" method="POST" name="links"> <select name="dropdown" value="options"> <option value"form.php">Select a Format</option> <option value="1.php">1</option> <option value="2.php">2</option> <option value="3.php">3</option> <option value="4.php">4</option> <option value="5.php">5</option> </select> <br/> <br/> <input type="submit" value="Submit Query"/> </body> </html> fourth part I, based on the above information... the user should have a page with a include("livesearch.php") for 1.php, but i will place livesearch.php code below... #livesearch.php $target_path = $target_path . basename($_FILES['uploadedfile']['tmp_name']); $xmlDoc=new DOMDocument(); $xmlDoc->load("uploader.ph"); $x=$xmlDoc->getElementsByTagName('link'); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of q>0 if (strlen($q)>0) { $hint=""; for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('PPC'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1) { //find a link matching the search text if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } else { $hint=$hint . "<br /><a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } } } } } // Set output to "no suggestion" if no hint were found // or to the correct values if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?> fourth part II, the above code will be part of 1.php... this part of the form will ideally return a livesearch query from the uploaded xml document for the checked boxes by an element's name. #form.php <html> <head> <script type="text/javascript"> function showResult(str) { if (str.length==0) { document.getElementById("livesearch").innerHTML=""; document.getElementById("livesearch").style.border="0px"; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("livesearch").innerHTML=xmlhttp.responseText; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","livesearch.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <?php echo "<form> Please place element1 # to search: <input type='text' size='30' onkeyup='showResult(this.value)' /> <div id='livesearch'></div> </form>"; // This is to collect box array value as global_variables is set off in PHP5 by default // // variable that will send $box information from the checkboxes named getXMLbox to // an variable array $box=$_POST['getXMLbox']; if(empty($box)) { echo("These are the boxes that WERE not selected: $box"); } else { $N = count($box); echo("These are the boxes that ARE selected: $N "); for($i=0; $i<$N; $i++) { echo($box[$i] . " "); } } while (list ($key,$val) = @each ($box)) { echo "$val,"; } echo "<form method=post action='simple.php'>"; echo "<table border='0' cellspacing='0' style='border-collapse: collapse' width='100' > <tr bgcolor='#ffffff'> <td width='25%'><input type=checkbox name=getXMLbox[] value='element1'></td> <td width='25%'> element1</td> </tr> <tr bgcolor='#ffffff'> <td width='25%'><input type=checkbox name=getXMLbox[] value='element2'></td> <td width='25%'> element2</td> </tr> <tr> <td><br/></td> </tr> <tr> <td colspan =6 align=center><input type=submit name=SubmitForm value='Submit Query'></form></td> </tr> </table>"; ?> finally, i'd like to parse the data with a php5 function and display the xml information onto the screeen or have a dialog box open up for a person to save as. #simple.php <?php /* we will use simpleXML to transfer xml data to parse and read xml data */ //load the xml file to $file $file = ($_FILES["file"]["name"]); #load xml data $xml = simplexml_load_file($file) or die ("The connection to could not load the XML document. Please try again. \n"); #display the entire document echo ('$xml'); ?> so basically, i'm a bit lost and not getting the right outcome that i'd like. can someone please assist? many thanks. How do I use curl to upload an image to this form? Code: [Select] <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } ?> <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" --> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><input type="file" name="image"></td></tr> <tr><td><input name="Submit" type="submit" value="upload"></td></tr> </table> </form> <form id="test" action="<?php $_POST['SERVER_SELF'] ?>" method="POST" enctype="multipart/form-data" > <div class="wrap"> <p>upload image here for Contact Page</p> <input type="file" name="image"> <br> <input name="about1" type="submit" value="Upload image"> <br> </div> </form> <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100000"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['about'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=contactbg.'.'.jpg; //the new name will be containing the full path where will be stored (images folder) $newname="C:/xampp/htdocs/Dirk-taat/wp-content/themes/dirktaat/images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['about']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['about1'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=aboutme_bg.'.'.png; //the new name will be containing the full path where will be stored (images folder) $newname="C:/../.../../.../../.../images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['about1']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } } ?> the above code works only for 1 upload box if more than one upload box it does not upload the file. Thanks |