PHP - Multiple Image Uploading
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 Similar TutorialsI 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, 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 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! 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 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> 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? Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. This site was moved over from one server to another server. The image upload function was working fine on the old server, but when the files etc. were moved over to the new server, this is the resulting error when trying to upload an image: HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request. This is what I generated in Chrome (using developer tools): Code: [Select] Request URL:http://thedogrescuersinc.ca/imagedog_panel.php?imageid=158 Request Method:POST Status Code:500 Internal Server Error Request Headersview source Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Cache-Control:max-age=0 Connection:keep-alive Content-Length:24564 Content-Type:multipart/form-data; boundary=----WebKitFormBoundary4zUh1NSdGFj27Fsy Cookie:user=4667623; PHPSESSID=dkb6a8tg4ck00dj9bg568vknj2 Host:thedogrescuersinc.ca Origin:http://thedogrescuersinc.ca Referer:http://thedogrescuersinc.ca/imagedog_panel.php?imageid=158 User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11 Query String Parametersview URL encoded imageid:158 Request Payload ------WebKitFormBoundary4zUh1NSdGFj27Fsy Content-Disposition: form-data; name="change_pic" 1 ------WebKitFormBoundary4zUh1NSdGFj27Fsy Content-Disposition: form-data; name="userfile"; filename="adopt_a_dog_oakville_ontario.jpg" Content-Type: image/jpeg ------WebKitFormBoundary4zUh1NSdGFj27Fsy Content-Disposition: form-data; name="change_pic" CLICK HERE TO UPLOAD IMAGE ------WebKitFormBoundary4zUh1NSdGFj27Fsy-- Response Headersview source Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Connection:close Content-Type:text/html; charset=UTF-8 Date:Wed, 29 Feb 2012 16:49:48 GMT Expires:Thu, 19 Nov 1981 08:52:00 GMT Pragma:no-cache Server:Apache Transfer-Encoding:chunked Any ideas, suggestions would be appreciated. When i registred and try to upload a picture it doesnt show the picture but only a little icon that the picture doesnt excist. this is my code: Code: [Select] if(!empty($_FILES['photo'])) { if ((($_FILES["photo"]["type"] == "image/gif") || ($_FILES["photo"]["type"] == "image/jpeg") || ($_FILES["photo"]["type"] == "image/pjpeg") || ($_FILES["photo"]["type"] == "image/png")) && ($_FILES["photo"]["size"] < 1048576)){ $fileName = $_FILES['photo']['name']; $tmpName = $_FILES['photo']['tmp_name']; $fileSize = $_FILES['photo']['size']; $fileType = $_FILES['photo']['type']; if(!get_magic_quotes_gpc()){ if(isset($fileName)) { $fileName = addslashes($fileName); } } $url = $_FILES['photo']['name']; $idir = "upload/"; // Path To Images Directory $tdir = "upload/thumbs/"; // Path To Thumbnails Directory $twidth = "125"; // Maximum Width For Thumbnail Images $theight = "125"; // Maximum Height For Thumbnail Images $simg = imagecreatefromjpeg($_FILES["photo"]["tmp_name"]); // Make A New Temporary Image To Create The Thumbanil From $currwidth = imagesx($simg); // Current Image Width $currheight = imagesy($simg); // Current Image Height if ($currheight > $currwidth) { // If Height Is Greater Than Width $zoom = $twidth / $currheight; // Length Ratio For Width $newheight = $theight; // Height Is Equal To Max Height $newwidth = $currwidth * $zoom; // Creates The New Width } else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) $zoom = $twidth / $currwidth; // Length Ratio For Height $newwidth = $twidth; // Width Is Equal To Max Width $newheight = $currheight * $zoom; // Creates The New Height } $dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail imagetruecolortopalette($simg, false, 256); // Create New Color Pallete $palsize = ImageColorsTotal($simg); for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image $colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use } imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It) imagejpeg($dimg, "$tdir" . $url); // Saving The Image $tmpName = "$tdir" . $url; $fp = fopen($tmpName, 'r'); $imgcontent = fread($fp, filesize($tmpName)); $imgcontent = addslashes($imgcontent); fclose($fp); unlink($tmpName); imagedestroy($simg); // Destroying The Temporary Image imagedestroy($dimg); // Destroying The Other Temporary Image Well i have a php script which i use to upload jpg or gif images only... I want that whenever user uploads an image of any resolution my script transforms it to 100*100 resolution.. What should i do... Here is my PHP Script... Code: [Select] $_FILES["file"]["name"]=$_SESSION['id'].".jpg"; if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000000)) { 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 " You have already uploaded your profile pic..."; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //rename("/upload/" . $_FILES["file"]["name"], "/upload/" . $_SESSION['id'] ); $_SESSION['result']="PROFILE SETUP SUCCESSFULL"; header('location:members.php'); } } } else { echo "Invalid file"; } } Hi guys Im trying to create a form which allows me to insert records into my database, and upload an image, the name of which will be stored in the database. I have the following code which inserts all the data into the db, except the image name and the image isnt uploaded either Code: [Select] <?php require_once('../Connections/pwnedbookv4.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO Games (gametitle, info, genre, releasedate, format) VALUES (%s, %s, %s, %s, %s)", GetSQLValueString($_POST['gametitle'], "text"), GetSQLValueString($_POST['info'], "text"), GetSQLValueString($_POST['genre'], "text"), GetSQLValueString($_POST['releasedate'], "date"), GetSQLValueString($_POST['format'], "text")); mysql_select_db($database_pwnedbookv4, $pwnedbookv4); $Result1 = mysql_query($insertSQL, $pwnedbookv4) or die(mysql_error()); } ?> <form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="form1" id="form1"> <table align="center"> <tr valign="baseline"> <td nowrap="nowrap" align="right">Gametitle:</td> <td><input name="gametitle" type="text" value="" size="50" maxlength="50" /></td> </tr> <tr valign="baseline"> <?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'])) { if($_POST['Submit'] == ""){ // submit empty die ("you must include a picture"); } //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="coverart/".$image_name; //Writes the information to the database mysql_query("UPDATE Games SET cover = '$image_name' WHERE gametitle= '$gametitle'"); //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; }}}} ?> <td nowrap="nowrap" align="right">Cover:</td> <td><input type="file" name="image"></td></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Info:</td> <td><input name="info" type="text" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Gen </td> <td><input type="text" name="genre" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Releasedate:</td> <td><input type="text" name="releasedate" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Format:</td> <td><input type="text" name="format" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> </td> <td><input type="submit" value="Submit" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> Can anybody see what im missing? Hi there. I am trying to make a simple script. I am tryng to make my friend a website so he can add his cars to an online showroom. I.E: one page to add the cars info and upload an image. then one page to display all the info. I currently have nailed adding the info to the database and showing it in an array but i am having trouble adding an upload box on the form...adding the image info to the db and then showing the image in the info array. This is the code i have: addcar.html *This contains the form to add the vehicle* <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><IMG SRC="vehicleadd.jpg"><IMG SRC="vehicleedit.jpg"><IMG SRC="vehicledelete.jpg"></CENTER> <CENTER><B>Add a Vehicle</B></CENTER> <BR> <form action="inserts.php" method="post" enctype="multipart/form-data"> <CENTER>Vehicle Name:</CENTER> <CENTER><input type="text" name="CarName"></CENTER> <br> <CENTER>Vehicle Type:</CENTER> <CENTER><input type="text" name="CarTitle"></CENTER> <br> <CENTER>Vehicle Price:</CENTER> <CENTER><input type="text" name="CarPrice"></CENTER> <br> <CENTER>Vehicle Mileage:</CENTER> <CENTER><input type="text" name="CarMiles"></CENTER> <br> <CENTER>Vehicle Description:</CENTER> <CENTER><textarea name="CarDescription" rows="10" cols="30"></textarea></CENTER> <br> <center>Upload Image</center> <CENTER><input type="file" name="image_file" /></CENTER> <BR> <CENTER><input type="Submit"></CENTER> </form> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> inserts.php *This page contains the coding* *Currently adds the data but not image* <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Vehicle Added</B></CENTER> <BR> <?php mysql_connect("localhost", "wormste1_barry", "barry") or die(mysql_error()); mysql_select_db("wormste1_barry") or die(mysql_error()); $CarName = mysql_real_escape_string(trim($_POST['CarName'])); $CarTitle = mysql_real_escape_string(trim($_POST['CarTitle'])); $CarPrice = mysql_real_escape_string(trim($_POST['CarPrice'])); $CarMiles = mysql_real_escape_string(trim($_POST['CarMiles'])); $CarDescription = mysql_real_escape_string(trim($_POST['CarDescription'])); if(isset($_POST['submit'])){ //directory in which your file will be uploaded $target_path = "images/"; $target_path = $target_path . basename( $_FILES['image_file']['name']); if(move_uploaded_file($_FILES['image_file']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['image_file']['name']). " has been uploaded"; //this is file name which you can store in database $file_name = $_FILES['image_file']['name']; /* Code for storing file name into db */ }else echo "Something went wrong =)"; } mysql_query("INSERT INTO cars (CarName, CarTitle, CarPrice, CarMiles, CarDescription) VALUES('$CarName', '$CarTitle', '$CarPrice', '$CarMiles', '$CarDescription' ) ") or die(mysql_error()); echo "The vehicle data has been added!"; ?> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> Just in case: showroom.php *The page to display the info (Array): <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Current Showroom</B></CENTER> <BR> <!-- VIEWING BIT --> <?php include('dbconnect.php') ?> <?php // Make a MySQL Connection $query = "SELECT * FROM cars"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "<TABLE CELLPADDING=0 CELLSPACING=0 WIDTH=100% BORDER=0>"; echo "<TR />"; echo "<TD WIDTH=30% VALIGN=TOP />"; echo " <IMG SRC=immg.gif /> "; echo "<br />"; echo "</TD>"; echo "<TD WIDTH=10 VALIGN=TOP />"; echo " "; echo "</TD>"; echo "<TD />"; echo "<font size=3 face=arial /><B >"; echo $row['CarPrice']; echo "</B><font size=2 face=arial />"; echo "<br />"; echo $row['CarTitle']; echo "<br />"; echo "Vehicle Type: "; echo $row['CarName']; echo "<br />"; echo "Vehicle Mileage: "; echo $row['CarMiles']; echo "<br />"; echo "Description: "; echo "<br />"; echo "<br />"; echo $row['CarDescription']; echo "<br />"; echo "</TD>"; echo "</TR>"; echo "</TABLE>"; echo "<hr WIDTH=100% COLOR=BLACK />"; } ?> <!-- END OF VIEWING BIT --> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> Really could use a helping hand . Ian Hi, This is my first post of PHP Freaks and your help would be greatly appreciated. I am currently creating a pinball fansite and I am having a really big problem. I have a page where users can input a pinball machine into my mysql database. Below is the code for this. The question I am asking is how do I edit this script so that I can upload an image with it? I have gone through various tutorials for days and days and days but cant seem to make it work with the code I have below. PLEASE CAN YOU HELP?? I have the following code for creating the pinball machine... Code: [Select] <?php //create_topic.php include 'connect.php'; include 'header.php'; echo '<h2>Create a Pinball Machine</h2>'; if($_SESSION['signed_in'] == false) { //the user is not signed in echo 'Sorry, you have to be <a href="signin.php">signed in</a> to create a pinball machine.'; } else { //the user is signed in if($_SERVER['REQUEST_METHOD'] != 'POST') { //the form hasn't been posted yet, display it //retrieve the categories from the database for use in the dropdown $sql = "SELECT cat_id, cat_name, cat_description FROM categories_pinballmachines"; $result = mysql_query($sql); if(!$result) { //the query failed, uh-oh :-( echo 'Error while selecting from database. Please try again later.'; } else { if(mysql_num_rows($result) == 0) { //there are no categories, so a topic can't be posted if($_SESSION['user_level'] == 1) { echo 'You have not created categories yet.'; } else { echo 'Before you can post a topic, you must wait for an admin to create some categories.'; } } else { echo '<form method="post" action="",enctype="multipart/form-data"> Name: <input type="text" name="topic_subject"><br /> Type:'; echo '<select name="topic_cat">'; while($row = mysql_fetch_assoc($result)) { echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>'; } echo '</select><br />'; echo 'Manufacturer: <input type="text" name="post_manufacturer"><br /> Release Date: <input type="text" name="post_releasedate"><br /> Number of Players: <input type="text" name="post_numberofplayers"><br /> Production: <input type="text" name="post_production"><br /><br /><br /> Concept by: <input type="text" name="post_conceptby"><br /> Design by: <input type="text" name="post_designby"><br /> Art by: <input type="text" name="post_artby"><br /> Dots/Animation by: <input type="text" name="post_dotsanimationby"><br /> Mechanics by: <input type="text" name="post_mechanicsby"><br /> Music by: <input type="text" name="post_musicby"><br /> Sound by: <input type="text" name="post_soundby"><br /> Software by: <input type="text" name="post_softwareby"><br /> <input type="submit" value="Create Pinball Machine" /> </form>'; } } } else { //start the transaction $query = "BEGIN WORK;"; $result = mysql_query($query); if(!$result) { //Damn! the query failed, quit echo 'An error occured while creating your topic. Please try again later.'; } else { //the form has been posted, so save it //insert the topic into the topics table first, then we'll save the post into the posts table $sql = "INSERT INTO topics_pinballmachines(topic_subject, topic_date, topic_cat, topic_by) VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "', NOW(), " . mysql_real_escape_string($_POST['topic_cat']) . ", " . $_SESSION['user_id'] . " )"; $result = mysql_query($sql); if(!$result) { //something went wrong, display the error echo 'An error occured while inserting your data. Please try again later.<br /><br />' . mysql_error(); $sql = "ROLLBACK;"; $result = mysql_query($sql); } else { //the first query worked, now start the second, posts query //retrieve the id of the freshly created topic for usage in the posts query $topicid = mysql_insert_id(); $sql = "INSERT INTO posts_pinballmachines(post_manufacturer, post_releasedate, post_numberofplayers, post_production, post_conceptby, post_designby, post_artby, post_dotsanimationby, post_mechanicsby, post_musicby, post_soundby, post_softwareby, post_date, post_topic, post_by) VALUES ('" . mysql_real_escape_string($_POST['post_manufacturer']) . "', '" . mysql_real_escape_string($_POST['post_releasedate']) . "', '" . mysql_real_escape_string($_POST['post_numberofplayers']) . "', '" . mysql_real_escape_string($_POST['post_production']) . "', '" . mysql_real_escape_string($_POST['post_conceptby']) . "', '" . mysql_real_escape_string($_POST['post_designby']) . "', '" . mysql_real_escape_string($_POST['post_artby']) . "', '" . mysql_real_escape_string($_POST['post_dotsanimationby']) . "', '" . mysql_real_escape_string($_POST['post_mechanicsby']) . "', '" . mysql_real_escape_string($_POST['post_musicby']) . "', '" . mysql_real_escape_string($_POST['post_soundby']) . "', '" . mysql_real_escape_string($_POST['post_softwareby']) . "', NOW(), " . $topicid . ", " . $_SESSION['user_id'] . " )"; $result = mysql_query($sql); if(!$result) { //something went wrong, display the error echo 'An error occured while inserting your post. Please try again later.<br /><br />' . mysql_error(); $sql = "ROLLBACK;"; $result = mysql_query($sql); } else { $sql = "COMMIT;"; $result = mysql_query($sql); //after a lot of work, the query succeeded! echo 'You have succesfully created <a href="topic_pinballmachines.php?id='. $topicid . '">your new pinball machines</a>.'; } } } } } include 'footer.php'; ?> and the following code is where the information is displayed... <?php //create_cat.php include 'connect.php'; include 'header.php'; $sql = "SELECT topic_id, topic_subject FROM topics_pinballmachines WHERE topics_pinballmachines.topic_id = " . mysql_real_escape_string($_GET['id']); $result = mysql_query($sql); if(!$result) { echo 'The topic could not be displayed, please try again later.'; } else { if(mysql_num_rows($result) == 0) { echo 'This topic doesn′t exist.'; } else { while($row = mysql_fetch_assoc($result)) { //display post data echo '<h2>PINBALL MACHINES</h2>'; echo '<table> <tr> <th colspan="2">' . $row['topic_subject'] . '</th> </tr>'; //fetch the posts from the database $posts_sql = "SELECT posts_pinballmachines.post_topic, posts_pinballmachines.post_manufacturer, posts_pinballmachines.post_releasedate, posts_pinballmachines.post_numberofplayers, posts_pinballmachines.post_production, posts_pinballmachines.post_conceptby, posts_pinballmachines.post_designby, posts_pinballmachines.post_artby, posts_pinballmachines.post_dotsanimationby, posts_pinballmachines.post_mechanicsby, posts_pinballmachines.post_musicby, posts_pinballmachines.post_soundby, posts_pinballmachines.post_softwareby, posts_pinballmachines.post_date, posts_pinballmachines.post_by, users.user_id, users.user_name FROM posts_pinballmachines LEFT JOIN users ON posts_pinballmachines.post_by = users.user_id WHERE posts_pinballmachines.post_topic = " . mysql_real_escape_string($_GET['id']); $posts_result = mysql_query($posts_sql); if(!$posts_result) { echo '<tr><td>The posts could not be displayed, please try again later.</tr></td></table>'; } else { while($posts_row = mysql_fetch_assoc($posts_result)) { echo ' <tr class="topic-post"> <td class="post-content2"><b>Manufacturer: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_manufacturer'])) . '</br></tr> <td class="post-content2"><b>Release Date: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_releasedate'])) . '</br></tr> <td class="post-content2"><b>Number of Players: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_numberofplayers'])) . '</br></tr> <td class="post-content2"><b>Production: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_production'])) . '</br></tr> <td class="post-content2"><b>Concept by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_conceptby'])) . '</br></tr> <td class="post-content2"><b>Design by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_designby'])) . '</br></tr> <td class="post-content2"><b>Art by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_artby'])) . '</br></tr> <td class="post-content2"><b>Dots/Animation by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_dotsanimationby'])) . '</br></tr> <td class="post-content2"><b>Mechanics by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_mechanicsby'])) . '</br></tr> <td class="post-content2"><b>Music by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_musicby'])) . '</br></tr> <td class="post-content2"><b>Sound by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_soundby'])) . '</br></tr> <td class="post-content2"><b>Software by: </b> <td class="post-content">' . htmlentities(stripslashes($posts_row['post_softwareby'])) . '</br></tr> </td> </tr>'; } } if(!$_SESSION['signed_in']) { echo '<tr><td colspan=2>You must be <a href="signin.php">signed in</a> to comment. You can also <a href="signup.php">sign up</a> for an account.'; } else { //show reply box echo '<tr><td colspan="2"><h2>Comment on this Pinball Machine:</h2><br /> <form method="post" action="reply.php?id=' . $row['topic_id'] . '"> <textarea name="reply-content"></textarea><br /><br /> <input type="submit" value="Submit reply" /> </form></td></tr>'; } //finish the table echo '</table>'; } } } include 'footer.php'; ?> Any questions please don't hesitate to ask? Thanks in advance Dan MOD EDIT: code tags added. Hi all, I have the following script which uploads 1 image per testimonial, and stores the url in the database, in a field named 'Images'. I have added more upload fields to my form and named them images 2,images 3 etc, and then i tried to copy the following code to upload the urls in to the extra fields i mage for the urls in the database, ('Images2','Images3' etc etc), but i am getting a blank page now. I even copied teh function and adjusted the names...eg $imgname2, 3 etc. Can anybody help me please? Here is the code that deals with the image upload Thanks Code: [Select] <p align="center"> </p> </body> <?php $con = mysql_connect("localhost","xxxxxxxxxxxxxxxxx","xxxxxxxxxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("xxxxxxxxxxxx", $con); $image_tmpname = $_FILES['images']['name']; $imgdir = "uploaded_images/"; $imgname = $imgdir.$image_tmpname; if(move_uploaded_file($_FILES['images']['tmp_name'], $imgname)) { list($width,$height,$type,$attr)= getimagesize($imgname); switch($type) { case 1: $ext = ".gif"; break; case 2: $ext = ".jpg"; break; case 3: $ext = ".png"; break; default: echo "Not acceptable format of image"; } $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('Error: ' . mysql_error()); } echo "<p align=center><b>1 testimonial added</b></p>"; mysql_close($con); ?> </html> hi once again, i got a form that uploads an image, checks formats and all that.. i need to add the filesize restriction. something like this: define ("max_size","20"); //<- 20kb size $size=filesize($_FILES['image']['tmp_name']) if ($size > max_size*1024){ echo "too big filesize"; } else { //...... } how do i put that code, into this code? : <?php $allowedfiletypes = array("jpeg","jpg","gif","png"); $uploadfolder = "uploads/" ; $thumbnailheight = 100; //in pixels $thumbnailfolder = $uploadfolder."thumbs/" ; $action = $_POST['action']; if ($action == "upload") { //echo "<p>Uploading image... " ; if(empty($_FILES['uploadimage']['name'])){ echo '<script type="text/javascript"> {alert("Pasirinkite faila");} </script>'; } else { $uploadfilename = $_FILES['uploadimage']['name']; $fileext = strtolower(substr($uploadfilename,strrpos($uploadfilename,".")+1)); if (!in_array($fileext,$allowedfiletypes)) { echo '<script type="text/javascript"> {alert("Blogas failo tipas");} </script>'; } else { $fulluploadfilename = $uploadfolder.$uploadfilename ; if (move_uploaded_file($_FILES['uploadimage']['tmp_name'], $fulluploadfilename)) { echo '<script type="text/javascript"> {alert("Failas irasytas");} </script>'; $im = imagecreatefromjpeg($fulluploadfilename); if (!$im) { echo '<script type="text/javascript"> {alert("Nepavyko sugeneruoti thumbnail");} </script>'; } else { $imw = imagesx($im); // uploaded image width $imh = imagesy($im); // uploaded image height $nh = $thumbnailheight; // thumbnail height $nw = round(($nh / $imh) * $imw); //thumnail width $newim = imagecreatetruecolor ($nw, $nh); imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ; $thumbfilename = $thumbnailfolder.$uploadfilename ; imagejpeg($newim, $thumbfilename) or die('<script type="text/javascript"> {alert("Nepavyko issaugoti thumbnail");} </script>'); } } else { echo '<script type="text/javascript"> {alert("Nepavyko issaugoti failo");} </script>'; } } } function watermark($original_image,$original_watermark,$destination="") { $image=imagecreatefromjpeg($original_image); list($imagewidth,$imageheight)=getimagesize($original_image); $watermark = imagecreatefrompng($original_watermark); list($watermarkwidth,$watermarkheight)=getimagesize($original_watermark); if($watermarkwidth>$imagewidth || $watermarkheight>$imageheight) { $water_resize_factor = $imagewidth / $watermarkwidth; $new_watermarkwidth = $watermarkwidth * $water_resize_factor; $new_watermarkheight = $watermarkheight * $water_resize_factor; $new_watermark = imagecreatetruecolor($new_watermarkwidth , $new_watermarkheight); imagealphablending($new_watermark , false); imagecopyresampled($new_watermark , $watermark, 0, 0, 0, 0, $new_watermarkwidth, $new_watermarkheight, $watermarkwidth, $watermarkheight); $watermarkwidth = $new_watermarkwidth; $watermarkheight = $new_watermarkheight; $watermark = $new_watermark; } $startwidth = ($imagewidth - $watermarkwidth) / 2; $startheight = ($imageheight - $watermarkheight) / 2; imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight); if(!empty($destination)) imagejpeg($image,$destination); else imagejpeg($image); } $original_directory = "uploads/thumbs/"; $watermarked_images = "uploads/thumbs/watermarkedthumbs/"; if ($handle = opendir($original_directory)) { while (false !== ($file = readdir($handle))) { /* exif_imagetype checks if our file is a .jpg file. See manual for more info */ if(!is_file($original_directory.$file)) continue; if(exif_imagetype($original_directory.$file)==2) { watermark($original_directory.$file,"watermark.png",$watermarked_images.$file); } } closedir($handle); } } ?> <form name="newad" method="post" enctype="multipart/form-data" action=""> <label for="file" id="label">Pasirinkti failą: </label> <input type="hidden" name="action" value="upload" /> <input type="file" name="uploadimage" id="file"> <input name="Submit" type="submit" value="įkelti" id="submit"> </form> i tried smth like this, but it shows some error ("Warning: filesize() [function.filesize]: stat failed for 1.jpg in") <?php /* $allowedfiletypes = array("jpeg","jpg","gif","png"); $uploadfolder = "uploads/" ; $thumbnailheight = 100; //in pixels $thumbnailfolder = $uploadfolder."thumbs/" ; */ define ("max_size","20"); $size=filesize($_FILES['uploadimage']['name']); /* $action = $_POST['action']; if ($action == "upload") { //echo "<p>Uploading image... " ; if(empty($_FILES['uploadimage']['name'])){ echo '<script type="text/javascript"> {alert("Pasirinkite faila");} </script>'; } else { $uploadfilename = $_FILES['uploadimage']['name']; $fileext = strtolower(substr($uploadfilename,strrpos($uploadfilename,".")+1)); if (!in_array($fileext,$allowedfiletypes)) { echo '<script type="text/javascript"> {alert("Blogas failo tipas");} </script>'; } else { $fulluploadfilename = $uploadfolder.$uploadfilename ; */ if ($size > max_size*1024){ echo '<script type="text/javascript"> {alert("Per didelis failas");} </script>'; } else { /* if (move_uploaded_file($_FILES['uploadimage']['tmp_name'], $fulluploadfilename)) { echo '<script type="text/javascript"> {alert("Failas irasytas");} </script>'; $im = imagecreatefromjpeg($fulluploadfilename); if (!$im) { echo '<script type="text/javascript"> {alert("Nepavyko sugeneruoti thumbnail");} </script>'; } else { $imw = imagesx($im); // uploaded image width $imh = imagesy($im); // uploaded image height $nh = $thumbnailheight; // thumbnail height $nw = round(($nh / $imh) * $imw); //thumnail width $newim = imagecreatetruecolor ($nw, $nh); imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ; $thumbfilename = $thumbnailfolder.$uploadfilename ; imagejpeg($newim, $thumbfilename) or die('<script type="text/javascript"> {alert("Nepavyko issaugoti thumbnail");} </script>'); } } else { echo '<script type="text/javascript"> {alert("Nepavyko issaugoti failo");} </script>'; } } } } function watermark($original_image,$original_watermark,$destination="") { $image=imagecreatefromjpeg($original_image); list($imagewidth,$imageheight)=getimagesize($original_image); $watermark = imagecreatefrompng($original_watermark); list($watermarkwidth,$watermarkheight)=getimagesize($original_watermark); if($watermarkwidth>$imagewidth || $watermarkheight>$imageheight) { $water_resize_factor = $imagewidth / $watermarkwidth; $new_watermarkwidth = $watermarkwidth * $water_resize_factor; $new_watermarkheight = $watermarkheight * $water_resize_factor; $new_watermark = imagecreatetruecolor($new_watermarkwidth , $new_watermarkheight); imagealphablending($new_watermark , false); imagecopyresampled($new_watermark , $watermark, 0, 0, 0, 0, $new_watermarkwidth, $new_watermarkheight, $watermarkwidth, $watermarkheight); $watermarkwidth = $new_watermarkwidth; $watermarkheight = $new_watermarkheight; $watermark = $new_watermark; } $startwidth = ($imagewidth - $watermarkwidth) / 2; $startheight = ($imageheight - $watermarkheight) / 2; imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight); if(!empty($destination)) imagejpeg($image,$destination); else imagejpeg($image); } $original_directory = "uploads/thumbs/"; $watermarked_images = "uploads/thumbs/watermarkedthumbs/"; if ($handle = opendir($original_directory)) { while (false !== ($file = readdir($handle))) { /* exif_imagetype checks if our file is a .jpg file. See manual for more info */ /* if(!is_file($original_directory.$file)) continue; if(exif_imagetype($original_directory.$file)==2) { watermark($original_directory.$file,"watermark.png",$watermarked_images.$file); } } closedir($handle); } } */ ?> any ideas? thanks Hi there, i want to remake a script that uploads a images in one folder to script that uploads images to folder that is equal with article id. Something like - main_folder/images/articles/$id/image.jpg ... But i don't understand how i can create it.. I don't understand how the script can know last id and move images to the folder. It's easy to add script that create folder but how the script can know latest id?.. Here is the code that process images. [It's from php fusion cms so maybe someone could not understand some things.] Thank you.. Maybe some one can give some advice how script can know latest id?. Code: [Select] if (isset($_POST['save'])) { $error = ""; $news_subject = stripinput($_POST['news_subject']); $news_cat = isnum($_POST['news_cat']) ? $_POST['news_cat'] : "0"; if (isset($_FILES['news_image']) && is_uploaded_file($_FILES['news_image']['tmp_name'])) { $image = $_FILES['news_image']; $image_name = stripfilename(str_replace(" ", "_", strtolower(substr($image['name'], 0, strrpos($image['name'], "."))))); $image_ext = strtolower(strrchr($image['name'],".")); if ($image_ext == ".gif") { $filetype = 1; } elseif ($image_ext == ".jpg") { $filetype = 2; } elseif ($image_ext == ".png") { $filetype = 3; } else { $filetype = false; } if (!preg_match("/^[-0-9A-Z_\.\[\]]+$/i", $image_name)) { $error = 1; } elseif ($image['size'] > $settings['news_photo_max_b']){ $error = 2; } elseif (!$filetype) { $error = 3; } else { $image_t1 = image_exists(IMAGES_N_T, $image_name."_t1".$image_ext); $image_t2 = image_exists(IMAGES_N_T, $image_name."_t2".$image_ext); $image_full = image_exists(IMAGES_N, $image_name.$image_ext); move_uploaded_file($_FILES['news_image']['tmp_name'], IMAGES_N.$image_full); if (function_exists("chmod")) { chmod(IMAGES_N.$image_full, 0644); } $imagefile = @getimagesize(IMAGES_N.$image_full); if ($imagefile[0] > $settings['news_photo_max_w'] || $imagefile[1] > $settings['news_photo_max_h']) { $error = 4; unlink(IMAGES_N.$image_full); } else { createthumbnail($filetype, IMAGES_N.$image_full, IMAGES_N_T.$image_t1, $settings['news_photo_w'], $settings['news_photo_h']); if ($settings['news_thumb_ratio'] == 0) { createthumbnail($filetype, IMAGES_N.$image_full, IMAGES_N_T.$image_t2, $settings['news_thumb_w'], $settings['news_thumb_h']); } else { createsquarethumbnail($filetype, IMAGES_N.$image_full, IMAGES_N_T.$image_t2, $settings['news_thumb_w']); } } } if (!$error) { $news_image = $image_full; $news_image_t1 = $image_t1; $news_image_t2 = $image_t2; } else { $news_image = ""; $news_image_t1 = ""; $news_image_t2 = ""; } } else { $news_image = (isset($_POST['news_image']) ? $_POST['news_image'] : ""); $news_image_t1 = (isset($_POST['news_image_t1']) ? $_POST['news_image_t1'] : ""); $news_image_t2 = (isset($_POST['news_image_t2']) ? $_POST['news_image_t2'] : ""); } } Me and a friend are working on a nice secure Image Upload Script. The Upload Class <?php class imageUploader { public $image; // [name], [type], [tmp_name], [error], [size] public $maxFileSize; public $imageExtension; public function __construct($image, $max_file_size) { $this->image = $image; $this->maxFileSize = $max_file_size; } public function isValidImage() { $validExts = array("gif" => "image/gif", "jpeg" => "image/jpeg", "png" => "image/png"); if(in_array(strtolower($this->image["type"]), $validExts) == true) { foreach($validExts as $name => $value) { if(strtolower($this->image["type"]) == $value) { $this->imageExtension = $name; break; } } return true; } else { return false; } } public function isValidSize() { if($this->image["size"] > $this->maxFileSize) { return false; } else { return true; } } public function uploadImage() { if($this->image["error"] > 0) { $errors[] = "An error has occurred"; } elseif($this->isValidImage() == false) { $errors[] = "Invalid file type. Only use JPG, GIF or PNG"; } elseif($this->isValidSize() == false) { $errors[] = "Max file size exceeded."; } if(count((array) $errors) == 0) { move_uploaded_file($this->image["tmp_name"], "Images/" . $this->generateName(rand(10, 15)) . time() . "." . $this->imageExtension); } else { echo implode("<br />", $errors); } } public function createThumbnails() { } public function resizeImage($size_y, $size_x) { } public function generateName($length) { $randstr = ""; for ($i = 0; $i < $length; $i++) { $randnum = mt_rand(0, 61); if ($randnum < 10) { $randstr .= chr($randnum + 48); } elseif ($randnum < 36) { $randstr .= chr($randnum + 55); } else { $randstr .= chr($randnum + 61); } } return $randstr; } } ?> The Everyday HTML Code: [Select] <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>Image</td> <td><input type="file" name="file" id="file" /></td> <td><input type="submit" name="submit" value="Submit" /></td> </tr> </table> </form> My friend did most of the work, but had to go to sleep. My problem is I have a deadline to finish this in under 3 hours for use on my website. What I need it to do is create thumbnails in a /Thumbnail/ sub-folder, with thumbnails being cropped to 100px x 100px. If the full image is larger than 600px x 600px they would have to be resized down to nothing more than 600px for the longest side. I wouldn't mind if they were 300px x 600px, just nothing larger than 600px. I'm willing to pay for this to be completed, I only have roughly $50 though. I know this isn't a freelance area, but it kind of suits this area too with a freelance option. After the upload script is done, I have to work on a php system to get the images and display them, so that I'm not directly linking images. So anyone got some spare time to help out? Hi all, I have been trying to create a thumbnail but have realised I can just resize the image instead. I have been trying to do this and have made the code below however do not know what else I need to do to upload the new image. Could someone help? Thanks <?php $filename = $_FILES['image']; $reg = "G-ZZZZ"; $width = 200; $height = 200; list($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig; } else { $height = $width/$ratio_orig; } $destination='aircraft/'.$reg."1.jpg"; $temp_file = $_FILES['image']['tmp_name']; move_uploaded_file($temp_file,$destination); ?> ok i have a image uploading script here, it works fine but theres one thing im unhappy with when i first downloaded it it had 1 working one, and the rest examples which you basically have to put together yourself with the sample code (doesen't work without adding missing coding), i have done all that then i took the time to add a random string prefix, im new at php so it took me awhile to work out which strings would work in the right area. now this is what i need help with, when it uploads it has two options, download and remove, these both work fine, but on the file uploader that does work it has "file uploaded to "http://site.com/image.png" the example of course did not work (had loading bar working, and etc but didn't upload or have the feature i just mentioned) and the coder of the script used javascript and inner html for the file uploaded.... etc, because it uploads without refreshing, only thing is i cant seem to get it to work with the new random string i put in, i tried to recreate one with the same type of thing they used for the filename but it didn't work well here is the code, hope you can help. image upload handler Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php $uploader=new PhpUploader(); if(@$_GET["download"]) { $fileguid=$_GET["download"]; $mvcfile=$uploader->GetUploadedFile($fileguid); header("Content-Type: application/oct-stream"); header("Content-Disposition: attachment; filename=\"" . $mvcfile->FileName . "\""); readfile($mvcfile->FilePath); } if(@$_POST["delete"]) { $fileguid=$_POST["delete"]; $mvcfile=$uploader->GetUploadedFile($fileguid); unlink($mvcfile->FilePath); echo("OK"); } if(@$_POST["guidlist"]) { $guidarray=explode("/",$_POST["guidlist"]); //OUTPUT JSON echo("["); $count=0; foreach($guidarray as $fileguid) { $mvcfile=$uploader->GetUploadedFile($fileguid); if(!$mvcfile) continue; //process the file here , move to some where //rename(...) if($count>0) echo(","); echo("{"); echo("FileGuid:'");echo($mvcfile->FileGuid);echo("'"); echo(","); echo("FileSize:'");echo($mvcfile->FileSize);echo("'"); echo(","); echo("FileName:'");echo($mvcfile->FileName);echo("'"); echo("}"); $count++; } echo("]"); } //USER CODE: $rand = substr(md5(microtime()),rand(0,26),10); $targetfilepath= 'savefiles/' . $rand->rand . $mvcfile->FileName; if( is_file ($targetfilepath) ) unlink($targetfilepath); $mvcfile->MoveTo( $targetfilepath ); exit(200); ?> image upload(with form to choose file) Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Ajax - Build attachments table </title> <link href="demo.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var handlerurl='ajax-attachments-handler.php' function CreateAjaxRequest() { var xh; if (window.XMLHttpRequest) xh = new window.XMLHttpRequest(); else xh = new ActiveXObject("Microsoft.XMLHTTP"); xh.open("POST", handlerurl, false, null, null); xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); return xh; } </script> <script type="text/javascript"> var fileArray=[]; function ShowAttachmentsTable() { var table = document.getElementById("filelist"); while(table.firstChild)table.removeChild(table.firstChild); AppendToFileList(fileArray); } function AppendToFileList(list) { var table = document.getElementById("filelist"); for (var i = 0; i < list.length; i++) { var item = list[i]; var row=table.insertRow(-1); row.setAttribute("fileguid",item.FileGuid); row.setAttribute("filename",item.FileName); var td1=row.insertCell(-1); td1.innerHTML="<img src='phpuploader/resources/circle.png' border='0'/>"; var td2=row.insertCell(-1); td2.innerHTML=item.FileName; var td4=row.insertCell(-1); td4.innerHTML="[<a href='"+handlerurl+"?download="+item.FileGuid+"'>download</a>]"; var td4=row.insertCell(-1); td4.innerHTML="[<a href='javascript:void(0)' onclick='Attachment_Remove(this)'>remove</a>]"; } } function Attachment_FindRow(element) { while(true) { if(element.nodeName=="TR") return element; element=element.parentNode; } } function Attachment_Remove(link) { var row=Attachment_FindRow(link); if(!confirm("Are you sure you want to delete '"+row.getAttribute("filename")+"'?")) return; var guid=row.getAttribute("fileguid"); var xh=CreateAjaxRequest(); xh.send("delete=" + guid); var table = document.getElementById("filelist"); table.deleteRow(row.rowIndex); for(var i=0;i<fileArray.length;i++) { if(fileArray[i].FileGuid==guid) { fileArray.splice(i,1); break; } } } function CuteWebUI_AjaxUploader_OnPostback() { var uploader = document.getElementById("myuploader"); var guidlist = uploader.value; var xh=CreateAjaxRequest(); xh.send("guidlist=" + guidlist); //call uploader to clear the client state uploader.reset(); if (xh.status != 200) { alert("http error " + xh.status); setTimeout(function() { document.write(xh.responseText); }, 10); return; } var list = eval(xh.responseText); //get JSON objects fileArray=fileArray.concat(list); AppendToFileList(list); } function ShowFiles() { var msgs=[]; for(var i=0;i<fileArray.length;i++) { msgs.push(fileArray[i].FileName); } alert(msgs.join("\r\n")); } </script> </head> <body> <div class="demo"> <h2>Building attachment table (AJAX)</h2> <p>This sample demonstrates how to build your own attachment table.</p> <?php $uploader=new PhpUploader(); $uploader->MaxSizeKB=10240; $uploader->Name="myuploader"; $uploader->MultipleFilesUpload=true; $uploader->InsertText="Select multiple files (Max 10M)"; $uploader->AllowedFileExtensions="*.jpg,*.png,*.gif,*.bmp,*.txt,*.zip,*.rar"; $uploader->Render(); ?> <br/><br/> <table id="filelist" style='border-collapse: collapse' class='Grid' border='0' cellspacing='0' cellpadding='2'> </table> <br/><br/> <button onclick="ShowFiles()">Show files</button> </div> <script type='text/javascript'> //this is to show the header.. ShowAttachmentsTable(); </script> <script type='text/javascript'> function CuteWebUI_AjaxUploader_OnTaskComplete(task) { var div=document.createElement("DIV"); var link=document.createElement("A"); link.setAttribute("href","savefiles/"+task.rand); link.innerHTML="You have uploaded file : savefiles/"+task.rand; link.target="_blank"; div.appendChild(link); document.body.appendChild(div); } </script> </body> </html> and here is the phpuploader.php file just in case |